问题描述
我刚刚开始使用pandas/matplotlib代替Excel来生成堆积的条形图.我遇到了问题
I just started using pandas/matplotlib as a replacement for Excel to generate stacked bar charts. I am running into an issue
(1)在默认的颜色表中只有5种颜色,因此,如果我有5种以上的类别,则颜色会重复.如何指定更多颜色?理想情况下,是具有开始颜色和结束颜色的渐变,以及动态生成介于两者之间的n种颜色的方法吗?
(1) there are only 5 colors in the default colormap, so if I have more than 5 categories then the colors repeat. How can I specify more colors? Ideally, a gradient with a start color and an end color, and a way to dynamically generate n colors in between?
(2)颜色在视觉上不太令人满意.如何指定一组自定义的n种颜色?或者,渐变也可以.
(2) the colors are not very visually pleasing. How do I specify a custom set of n colors? Or, a gradient would also work.
以下示例说明了以上两点:
An example which illustrates both of the above points is below:
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
函数.
You can specify the color
option as a list directly to the plot
function.
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值定义颜色项,等等.这样做可能会变得很复杂. /p>
To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.
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.
最后一个示例为我生成了以下简单的颜色渐变:
The last example yields the follow simple gradient of colors for me:
我玩的时间还不够长,无法弄清楚如何强制图例使用已定义的颜色,但是我敢肯定您可以做到.
I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.
但是,通常,很大的建议是直接使用Matplotlib中的函数.从Pandas调用它们是可以的,但是我发现您有更好的选择和性能,直接从Matplotlib调用它们.
In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.
这篇关于如何给 pandas /matplotlib条形图自定义颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!