饼图的标签是字符串。

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

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:

饼图的标签是字符串。

饼图的标签是字符串。

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:

确定