matplotlib 饼图的标签是字符串

56lgkhnf  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(103)

我有一系列饼图的情节和类别(标签)是字符串。即使标签是字符串而不是整数,我如何仍然绘制饼图?

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()
t1qtbnec

t1qtbnec1#

您可以:

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()

此代码使用一个颜色Map表来保持所有图表上每个标签的颜色相同。
输出:

相关问题