为熊猫饼图系列匹配切片的着色

时间:2020-05-14 21:49:41

标签: pandas matplotlib pandas-groupby

我有一个熊猫数据框,看起来像这样:

df = pd.DataFrame( {'Judge': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3}, 'Category': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'B', 5: 'C', 6: 'A', 7: 'B', 8: 'C'}, 'Rating': {0: 'Excellent', 1: 'Very Good', 2: 'Good', 3: 'Very Good', 4: 'Very Good', 5: 'Very Good', 6: 'Excellent', 7: 'Very Good', 8: 'Excellent'}} )

我正在绘制一个饼图以显示每个法官的评分,如下所示:

grouped = df.groupby('Judge')

for group in grouped:
    group[1].Rating.value_counts().plot(kind='pie', autopct="%1.1f%%")
    plt.legend(group[1].Rating.value_counts().index.values, loc="upper right")
    plt.title('Judge ' + str(group[0]))
    plt.axis('equal')
    plt.ylabel('')
    plt.tight_layout()
    plt.show()

不幸的是,每个法官的切片颜色都不相同。例如,法官1的“ Excellent”切片为蓝色,而法官2的“非常好”切片为蓝色。

如何在图与图之间强制执行切片颜色一致性?

1 个答案:

答案 0 :(得分:1)

我认为您可以拆堆并作图:

axes = (df.groupby('Judge').Rating.value_counts()
   .unstack('Judge')
   .plot.pie(subplots=True, figsize=(6,6), layout=(2,2))
)

# do some thing with the axes
for ax in axes.ravel():
    pass

输出:

enter image description here

相关问题