您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

其他 2022/1/1 18:28:29 有468人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶