饼图的标签是字符串。

huangapple go评论103阅读模式
英文:

labels of pie chart are strings

问题

有一系列要绘制的饼图,类别(标签)是字符串。即使标签是字符串而不是整数,我仍然可以绘制饼图吗?

  1. df = pd.DataFrame({'Kanton': ['AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH'],
  2. 'Kat': ['1b','4','5','6','1c','4','2a','3','3','3','2b','5','1d']})
  3. kantone = df['Kanton'].unique()
  4. for i in kantone:
  5. df_n = df.loc[df['Kanton'] == i, 'Kat'].value_counts()
  6. data = df_n
  7. labels = df_n.index.values
  8. colors = sns.color_palette("bright", len(df['Kat'].unique()))
  9. plt.pie(data, labels=labels, colors=[colors[k-1] for k in labels], autopct='%.0f%%')
  10. plt.title("Kanton " + i)
  11. 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?

  1. df = pd.DataFrame({'Kanton': ['AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH'],
  2. 'Kat': ['1b','4','5','6','1c','4','2a','3','3','3','2b','5','1d']})
  3. kantone=df['Kanton'].unique()
  4. for i in kantone:
  5. #print(i)
  6. df_n=df.loc[df['Kanton'] == i, 'Kat'].value_counts()
  7. #print(df_n)
  8. #define data
  9. data = df_n
  10. labels = df_n.index.values
  11. colors = sns.color_palette("bright", len(df['Kat'].unique()))
  12. #plot
  13. plt.pie(data, labels = labels, colors=[colors[k-1] for k in labels], autopct='%.0f%%')
  14. plt.title("Kanton " + i)
  15. plt.show()

答案1

得分: 0

这段代码使用颜色映射在所有图表中为每个标签保持相同的颜色。

输出:

饼图的标签是字符串。

饼图的标签是字符串。

英文:

You can do:

  1. labels = df['Kat'].unique()
  2. colors = sns.color_palette("bright", len(labels))
  3. color_map = dict(zip(labels, colors))
  4. for i in kantone:
  5. df_n = df.loc[df['Kanton'] == i, 'Kat'].value_counts()
  6. plt.pie(df_n, labels=df_n.index, colors=df_n.index.map(color_map), autopct='%.0f%%')
  7. plt.title("Kanton " + i)
  8. plt.show()

This code uses a color map to keep the same color for each label on all charts.

Output:

饼图的标签是字符串。

饼图的标签是字符串。

huangapple
  • 本文由 发表于 2023年5月7日 02:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定