在Python中绘制条形图,Y轴为百分值,条上方文本为计数值
我有一个数据框(df),内容如下:
data = {
'class': ['First', 'First', 'First', 'Second', 'Second', 'Second', 'Third', 'Third', 'Third'],
'who': ['child', 'man', 'woman', 'child', 'man', 'woman', 'child', 'man', 'woman'],
'survived': [5, 42, 89, 19, 8, 60, 25, 38, 56],
'Percentage': [10.204082, 47.727273, 43.414634, 38.775510, 9.090909, 29.268293, 51.020408, 43.181818, 27.317073]
}
# Create DataFrame
df = pd.DataFrame(data)
class who survived Percentage
0 First child 5 10.204082
1 First man 42 47.727273
2 First woman 89 43.414634
3 Second child 19 38.775510
4 Second man 8 9.090909
5 Second woman 60 29.268293
6 Third child 25 51.020408
7 Third man 38 43.181818
8 Third woman 56 27.317073
有人能帮我写一段用seaborn库的代码吗?我想要一个柱状图,按照“class”这个分类来分组,顺序是:["First","Second","Third"]
。同时,柱状图内部还要根据:["child","man","woman"]
来进一步分组。
在y轴上,我希望显示生存的百分比。
而且我想让每个柱子顶部显示实际的“生存”值。
最后,生成的图应该看起来像这样:
这是我目前写的代码:
# Plot
ax = sns.barplot(x='class', y='Percentage', hue='who', data=data, estimator=sum, ci=None)
ax.set(ylabel='Survived Count', title='Survived Count and Percentage')
1 个回答
1
根据重复的问题:
fig, ax = plt.subplots(figsize=(9, 7))
sns.barplot(x='class', y='Percentage', hue='who', data=df, ax=ax)
sns.move_legend(ax, bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
# get the unique values for hue
hue_col = df.who.unique()
# iterate through each group of containers - in order by hue groups
for c, col in zip(ax.containers, hue_col):
# use the column and bar height to get the correct value for name
labels = [f"{df.loc[(df.who.eq(col) & df.Percentage.eq(h)), 'survived'].iloc[0]}" if (h := v.get_height()) > 0 else '' for v in c ]
# add the survived annotation to the top of the bar
ax.bar_label(c, labels=labels, padding=3) # rotation=90 if needed
# pad the spacing between the number and the edge of the figure
ax.margins(y=0.1)