如何更改堆叠pyplot图表的列颜色以指示另一列是否为真?

2024-06-01 07:38:34 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是数据框中的一些示例数据

Country      restricted  V1%      V2%
0   Algeria  True    39.575812    60.424188
1   Angola   True    56.931682    43.068318
2   Argent   False    15.555556   84.4444

我使用堆叠条形图来显示3个值。V1和V2已标准化为%ges,因此创建如下基本图表很简单:

xx=df.plot(kind="bar", x='Country',stacked=True,figsize=(20,10);

之前已经订购了数据帧

df=conjoint_ag_df.sort_values(['restricted',.Country'], ascending=[False,True])

以便按国家和真/假值显示

这给了我一个这样的基本显示

enter image description here

我试图做的是将所有列中的真值限制为一个颜色对,而那些假值限制为另一个颜色对-因为我首先按限制排序,这意味着颜色将沿图形的x轴从前者更改为后者。我可以按照下面的示例对简单的条形图执行此操作

Color matplotlib bar chart based on value

对于使用此选项的一对颜色

xx=_df.plot(kind="bar", x='Country',stacked=True,figsize=(20,10),color=['r','b'])

(可怕)但我不知道如何对列应用微分器,根据真假值将两个颜色值更改为两个不同的值


Tags: 数据falsetrue示例dfplot颜色bar
2条回答

也许这不是最漂亮的方法,但它是有效的。我正在使用来自plot方法的关键字参数color。作为参数,我们可以根据'restricted'条件为您创建一个字典。我使用了matplotlib colormaps中定义的一些内置颜色,但您可以使用自己选择的颜色,当然:

from matplotlib import cm

palette1 = cm.get_cmap('autumn', 2)
palette2 = cm.get_cmap('winter', 2)

colors = {
    'V1': [palette1(0) if restricted else palette2(0) for restricted in df['restricted']],
    'V2': [palette1(1) if restricted else palette2(1) for restricted in df['restricted']]
}

xx = df.plot(kind="bar", x='Country', stacked=True, color=colors, legend=False, figsize=(20, 10))

因为这会弄乱默认的图例,所以我尝试制作一个(虽然不是最漂亮的):

from matplotlib.lines import Line2D

custom_legend = [
    Line2D([0], [0], color=palette1(0), lw=3),
    Line2D([0], [0], color=palette1(1), lw=3),
    Line2D([0], [0], color=palette2(0), lw=3),
    Line2D([0], [0], color=palette2(1), lw=3),
]

plt.legend(custom_legend, ['V1 (Restricted)', 
                           'V2 (Restricted)', 
                           'V1 (Non-Restricted)', 
                           'V2 (Non-Restricted'])

plt.show()

这为我们提供了以下图形作为输出:

enter image description here

可能有更好的方法,但这里有一种使用循环的方法:

for idx, row in df.iterrows():
    color = ['tab:blue', 'tab:orange'] if row['restricted'] else ['tab:blue', 'tab:red']
    plt.bar(row['Country'], row['V1%'], color=color[0])
    plt.bar(row['Country'], row['V2%'], bottom=row['V1%'], color=color[1])

输出:

enter image description here

相关问题 更多 >