英文:
labels of pie chart are strings
问题
有一系列要绘制的饼图,类别(标签)是字符串。即使标签是字符串而不是整数,我仍然可以绘制饼图吗?
df = pd.DataFrame({'Kanton': ['AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH'],
'Kat': ['1b','4','5','6','1c','4','2a','3','3','3','2b','5','1d']})
kantone = df['Kanton'].unique()
for i in kantone:
df_n = df.loc[df['Kanton'] == i, 'Kat'].value_counts()
data = df_n
labels = df_n.index.values
colors = sns.color_palette("bright", len(df['Kat'].unique()))
plt.pie(data, labels=labels, colors=[colors[k-1] for k in labels], autopct='%.0f%%')
plt.title("Kanton " + i)
plt.show()
英文:
I have a series of pie chart to plot and the categories (labels) are strings. How can I still plot the pie charts even if the labels are strings and not integers?
df = pd.DataFrame({'Kanton': ['AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH'],
'Kat': ['1b','4','5','6','1c','4','2a','3','3','3','2b','5','1d']})
kantone=df['Kanton'].unique()
for i in kantone:
#print(i)
df_n=df.loc[df['Kanton'] == i, 'Kat'].value_counts()
#print(df_n)
#define data
data = df_n
labels = df_n.index.values
colors = sns.color_palette("bright", len(df['Kat'].unique()))
#plot
plt.pie(data, labels = labels, colors=[colors[k-1] for k in labels], autopct='%.0f%%')
plt.title("Kanton " + i)
plt.show()
答案1
得分: 0
这段代码使用颜色映射在所有图表中为每个标签保持相同的颜色。
输出:
英文:
You can do:
labels = df['Kat'].unique()
colors = sns.color_palette("bright", len(labels))
color_map = dict(zip(labels, colors))
for i in kantone:
df_n = df.loc[df['Kanton'] == i, 'Kat'].value_counts()
plt.pie(df_n, labels=df_n.index, colors=df_n.index.map(color_map), autopct='%.0f%%')
plt.title("Kanton " + i)
plt.show()
This code uses a color map to keep the same color for each label on all charts.
Output:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论