如何给熊猫/ matplotlib条形图自定义颜色


问题内容

我刚开始使用pandas / matplotlib替代Excel来生成堆积的条形图。我遇到了一个问题

(1)默认颜色表中只有5种颜色,因此如果我的类别超过5种,则颜色会重复。如何指定更多颜色?理想情况下,具有起始颜色和结束颜色的渐变,以及在两者之间动态生成n种颜色的方法?

(2)颜色在视觉上不太令人满意。如何指定一组自定义的n种颜色?或者,渐变也将起作用。

下面的示例说明了以上两个方面:

  4 from matplotlib import pyplot
  5 from pandas import *
  6 import random
  7 
  8 x = [{i:random.randint(1,5)} for i in range(10)]
  9 df = DataFrame(x)
 10 
 11 df.plot(kind='bar', stacked=True)

输出是这样的:

在此处输入图片说明


问题答案:

您可以将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调用它们。