Python matplotlib,如何对条形图进行分组

2024-06-08 07:33:58 发布

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

你能帮我完成以下任务吗

我需要这样的输出: https://prnt.sc/11e7rcq(当然颜色并不重要,只是我想要的结果的一个例子)

但是我得到了另一个输出。。我的结果在代码中,错误是什么

df = pd.DataFrame(
    {
        'pension': [0,0,1,1],
        'sex': ['female','male','female','male'],
        'count': [2,3,3,1]
    }
)
labels = df['sex'].tolist()
count = df['count'].tolist()
pension = df['pension'].tolist()

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, count, width, label='Men')
rects2 = ax.bar(x + width/2, pension, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)

fig.tight_layout()

plt.show()

Tags: thedflabelscountfigbaraxwidth
1条回答
网友
1楼 · 发布于 2024-06-08 07:33:58

您可以执行以下操作:

import seaborn as sns
pension = [0,0,1,1]
count = [2, 3,3,1]
sex = ['female','male','female','male',]
df = pd.DataFrame({'pension': pension,
                    'count': count,
                  "sex": sex})

sns.barplot(x="sex", y="count", hue="pension", data=df)

结果如下:

enter image description here

相关问题 更多 >

    热门问题