Python 如何在饼图 matplotlib 上生成更多颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21034830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:51:58  来源:igfitidea点击:

How can I generate more colors on pie chart matplotlib

pythonmatplotlibpie-chart

提问by user3001937

I am having more then 40 items to show in my chart. I have only 10 colours that repeatedly are shown on the chart. How can I generate more colors.

我有超过 40 个项目要显示在我的图表中。我只有 10 种颜色在图表上重复显示。我怎样才能产生更多的颜色。

plt.pie(f,labels=labels,autopct='%1.1f%%', startangle=90,shadow=True)

I should add "color=colors" where colors is generated infinitely ?

我应该在无限生成颜色的地方添加“color=colors”吗?

回答by CT Zhu

You need colorsargument, beside that you can use some color maps from cm.

您需要colors参数,此外您可以使用cm.

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> import numpy as np
>>> a=np.random.random(40)
>>> cs=cm.Set1(np.arange(40)/40.)
>>> f=plt.figure()
>>> ax=f.add_subplot(111, aspect='equal')
>>> p=plt.pie(a, colors=cs)
>>> plt.show()

enter image description here

在此处输入图片说明

Beside using colormaps, also consider using .set_color_cycle()method. See this post: plotting different colors in matplotlib

除了使用颜色图,还要考虑使用.set_color_cycle()方法。请参阅这篇文章:在 matplotlib 中绘制不同的颜色

回答by DecaX

If your pie chart is coming out with grouped chunks of the same colour when utilising the solution above, try changing the colour map from 'Set1' to any map you like from the following link: https://matplotlib.org/examples/color/colormaps_reference.html

如果您的饼图在使用上述解决方案时出现具有相同颜色的分组块,请尝试通过以下链接将颜色图从“Set1”更改为您喜欢的任何地图:https: //matplotlib.org/examples/color /colormaps_reference.html

As for randomising the colours, I suggest that you randomise the cs array in the solution above. But that doesn't really give a nice spectrum of colours.

至于随机化颜色,我建议你在上面的解决方案中随机化 cs 数组。但这并没有真正提供一个很好的颜色光谱。

回答by Gags08

I hope this answer would be useful. Check this link , Matplotlib supported colors. You can randomly pick 40 colors from it and use in your pie chart.

我希望这个答案会有用。检查此链接, Matplotlib 支持颜色。您可以从中随机选择 40 种颜色并在饼图中使用。

mcolors.TABLEAU_COLORS
mcolors.BASE_COLORS
mcolors.CSS4_COLORS

Sample

样本

import random
import matplotlib.colors as mcolors
colors = random.choices(list(mcolors.CSS4_COLORS.values()),k = number_of_colors)