【问题标题】:Keep same color for each label in different pie charts在不同的饼图中为每个标签保持相同的颜色
【发布时间】:2020-06-13 12:39:21
【问题描述】:

我无法为从一个饼图到另一个饼图的每个标签保持相同的颜色。正如您在下图中看到的,Matplotlib 反转了第二个饼图中的颜色。我想为“Frogs”标签保留红色,为“Hogs”标签保留绿色。 我还尝试添加 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)

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以定义一个颜色字典,然后在绘图时使用此映射分配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()])
    

    【讨论】:

    • 这可行,但不幸的是你需要在代码中硬编码你的值,否则我猜有一个函数可以生成你的颜色字典。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    相关资源
    最近更新 更多