您可以将color
选项指定为直接指向该plot
功能的列表。
from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np # I find np.random.randint to be better
# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)
# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))
# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)
要定义自己的自定义列表,您可以执行以下操作,或者只是查找Matplotlib技术以通过其RGB值定义颜色项,等等。您可能会因此而变得复杂。
my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.
我玩的时间还不够长,无法弄清楚如何强制图例使用已定义的颜色,但是我敢肯定您可以做到。
但是,总的来说,很大的建议是直接使用Matplotlib中的函数。从Pandas调用它们是可以的,但是我发现您有更好的选择和性能,直接从Matplotlib调用它们。