gpt4 book ai didi

python - 如何为图例的个体值设置独特的颜色

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:05 24 4
gpt4 key购买 nike

我的堆积条形图中有很多图例,我注意到图例中的颜色是重复的,所以我很难根据图例区分图表中的真实值,所以我想为每个图例设置唯一的颜色传说中的值(value),为此,我做了很多研究,有些不起作用,有些很难理解示例 this当我使用这个时,我收到一个错误,'AxesSubplot'对象没有属性'set_color_cycle'那么有没有一种简单有效的方法

我不想要单独为每个元素应用颜色的代码,因为我的数据集很大,这里是我的代码以获取有关我的图的更多详细信息

例如

#suppose I have data of few cites and their complaints 
city = ['NEW YORK', 'ASTORIA', 'BRONX', 'BRONX', 'ELMHURST', 'BROOKLYN',
'NEW YORK', 'BRONX', 'KEW GARDENS', 'BROOKLYN']
complaints = ['Noise - Street/Sidewalk', 'Blocked Driveway', 'Blocked Driveway',
'Illegal Parking', 'Illegal Parking', 'Illegal Parking',
'Illegal Parking', 'Blocked Driveway', 'Illegal Parking',
'Blocked Driveway']
# and from this I have created a stack bar chart
cmpltnt_rela = test2.groupby(['City', 'Complaint Type']).size().unstack().fillna(0).plot(kind='bar', legend = True, stacked=True)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5),ncol=2)
cmpltnt_rela.plot(figsize=(18,14))

其结果看起来像这样,您可以注意到图例的元素颜色 enter image description here

最佳答案

您可以创建一个长度与唯一投诉数量相同的颜色列表。例如gist_ncar。在代码中,我打乱了颜色的顺序,以降低相似颜色接近的可能性。

请注意,很难有超过 20 种视觉上足够不同的颜色。不同的人、不同的显示器可能会导致颜色难以区分。

Thisthis帖子提供了更多选择足够颜色的想法。在您的情况下,用相似的色调为相似的投诉着色可能会很有趣。

由于您的示例代码没有提供足够的数据,下面的代码会生成一些随机数。

import pandas as pd
from matplotlib import pyplot as plt
import random
import matplotlib as mpl

city = ['Londen', 'Paris', 'Rome', 'Brussels', 'Cologne', 'Madrid',
'Athens', 'Geneva', 'Oslo', 'Barcelona', 'Berlin']
complaints = list('abcdefghijklmnopqrstuv')

N = 100
city_column = random.choices(city, k=N)
complaints_column = random.choices(complaints, k=N)
test2 = pd.DataFrame({'City': city_column, 'Complaint Type': complaints_column})

# take a colormap with many different colors and sample it at regular intervals
cmap = plt.cm.gist_rainbow
norm = mpl.colors.Normalize(vmin=0, vmax=len(complaints) - 1)
colors = [cmap(norm(i)) for i in range(len(complaints))]

# create a stack bar chart
cmpltnt_rela = test2.groupby(['City', 'Complaint Type']).size().unstack().fillna(0).plot(kind='bar',
legend=True, stacked=True, color=colors)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2)
cmpltnt_rela.plot(figsize=(18, 14))
plt.tick_params('x', labelrotation=30)

plt.tight_layout()
plt.show()

example plot

关于python - 如何为图例的个体值设置独特的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59840519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com