条形图图例基于组的非值条形着色

问题描述 投票:1回答:2

我已经按照here的说明创建了条形图,其中有多个变量(在“值”列中指示),它们属于重复组。我已经按照他们的组成员身份对酒吧进行了着色。

我想创建一个最终相​​当于颜色字典的图例,显示与给定组成员资格相对应的颜色。

此处的代码:

d = {'value': [1, 2, 4, 5, 7 ,10], 'group': [1, 2, 3, 2, 2, 3]}
df = pd.DataFrame(data=d)
colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])
plt.legend(df['group'])

通过这种方式,我得到的是只有一种颜色(1)而不是(1、2、3)的图例。

谢谢!

python pandas matplotlib bar-chart
2个回答
1
投票

使用大熊猫,您可以如下创建your own legend

from matplotlib import pyplot as plt
from matplotlib import patches as mpatches
import pandas as pd

d = {'value': [1, 2, 4, 5, 7 ,10], 'group': [1, 2, 3, 2, 2, 3]}
df = pd.DataFrame(data=d)
colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])

handles = [mpatches.Patch(color=colors[i]) for i in colors]
labels = [f'group {i}' for i in colors]
plt.legend(handles, labels)

plt.show()

result


0
投票

您可以使用sns

sns.barplot(data=df, x=df.index, y='value', 
            hue='group', palette=colors, dodge=False)

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.