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

2024-04-25 07:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有40多个项目显示在我的图表。 我只有10种颜色反复出现在图表上。我怎样才能产生更多的颜色。

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

我应该添加“color=colors”,其中颜色是无限生成的?


Tags: 项目truelabels颜色图表pltcolorcolors
3条回答

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

至于颜色的随机化,我建议您在上面的解决方案中随机化cs阵列。但这并不能提供一个很好的颜色光谱。

您需要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

除了使用颜色映射,还可以考虑使用.set_color_cycle()方法。看这篇文章:plotting different colors in matplotlib

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

mcolors.TABLEAU_COLORS
mcolors.BASE_COLORS
mcolors.CSS4_COLORS

样品

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

相关问题 更多 >