mob*_*cen 3 python matplotlib pandas
我无法为从一个饼图到另一个饼图的每个标签保持相同的颜色。如下图所示,Matplotlib 反转了第二个饼图中的颜色。我想为“青蛙”标签保留红色,为“猪”标签保留绿色。我也尝试添加label参数,但它只是给出了错误的计数。我还尝试反转第二张图表中的颜色,colors=colors[::-1]但它有效但不可持续,因为有时我有两个以上的标签。

这是代码:
sizes1 = ['Frogs', 'Hogs', 'Frogs', 'Frogs']
sizes2 = ['Hogs', 'Hogs', 'Hogs', 'Frogs', 'Frogs']
colors=['red', 'green']
df1 = pd.DataFrame(data=sizes1, columns=['a'])
df2 = pd.DataFrame(data=sizes2, columns=['a'])
fig, ax = plt.subplots(1, 2, figsize=(18,5))
df1['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True, colors=colors)
df2['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[1],shadow=True, colors=colors)
Run Code Online (Sandbox Code Playgroud)
您可以定义一个颜色字典,然后使用此映射来分配colors绘图。这将使所有子图的配色方案保持一致。
colors={'Frogs':'red',
'Hogs':'green'}
df1['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True,
colors=[colors[v] for v in df1['a'].value_counts().keys()])
df2['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[1],shadow=True,
colors=[colors[v] for v in df2['a'].value_counts().keys()])
Run Code Online (Sandbox Code Playgroud)