matplotlib 一系列饼图,总是有一些颜色的相同标签

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

我有一个Pandasdataframe,我想生成一个饼图为每一个'坎顿'与频率的价值观'凯特'。并不是每个“Kat”都出现在每个“Kanton”中。我怎样才能使'kat'中的值始终具有相同的颜色呢?

df = pd.DataFrame({'Kanton': ['AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH'],
           'Kat': [1,4,5,6,1,4,2,3,3,3,2,5,1]})

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

   #plot
   plt.pie(data, labels = labels, autopct='%.0f%%')
   plt.title("Kanton " + i)
   plt.show()
ymzxtsji

ymzxtsji1#

您需要为ech Kanton指定颜色:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'Kanton': ['AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'AG', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH', 'ZH'],
           'Kat': [1,4,5,6,1,4,2,3,3,3,2,5,1]})

colors = sns.color_palette("bright", len(df['Kat'].unique()))

kantone = df['Kanton'].unique()
for i in kantone:
    print(i)
    df_n = df.loc[df['Kanton'] == i, 'Kat'].value_counts()
    data = df_n
    labels = df_n.index.values

    plt.pie(data, labels=labels, colors=[colors[k-1] for k in labels], autopct='%.0f%%')
    plt.title("Kanton " + i)
    plt.show()

相关问题