Python 向sns.countplot添加百分比-如何显示类别中两个值的百分比?

Python 向sns.countplot添加百分比-如何显示类别中两个值的百分比?,python,seaborn,Python,Seaborn,您好,我正在尝试向我的countplot添加5个类别和2个值(老的和年轻的)的百分比。我已尝试从添加def和循环 我的代码: plt.figure(figsize =(7,5)) ax = sb.countplot(data = df_x_1, x = 'concern_virus', hue = 'age') plt.xticks(size =12) plt.xlabel('Level of Concern', size = 14) plt.yticks(size = 12) plt.yla

您好,我正在尝试向我的
countplot
添加5个类别和2个值(老的和年轻的)的百分比。我已尝试从添加def和循环

我的代码:

plt.figure(figsize =(7,5))
ax = sb.countplot(data = df_x_1, x = 'concern_virus', hue = 'age')
plt.xticks(size =12)
plt.xlabel('Level of Concern', size = 14)
plt.yticks(size = 12)
plt.ylabel('Number of People', size = 12)
plt.title("Older and Younger People's Concern over the Virus", size = 16)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right");

for p in ax.patches:
    percentage = '{:.1f}%'.format(100 * p.get_height()/total)
    x = p.get_x() + p.get_width()
    y = p.get_height()
    ax.annotate(percentage, (x, y),ha='center')
plt.show()


如您所见,百分比没有意义。

问题似乎在于上述代码中未定义的变量:
total
total
应该是您想要调用的
100%
,例如数据帧中的行总数。这样,所有显示的百分比总和为100

以下是一些示例代码:

导入matplotlib.pyplot作为plt
作为pd进口熊猫
将numpy作为np导入
导入seaborn作为sns
N=250
df_x_1=pd.DataFrame({'concern_virus':np.random.choice(['a','b','c','d','e'],N),
'age':np.random.choice(['yourger','older'],N)})
plt.图(figsize=(7,5))
ax=sns.countplot(数据=df_x_1,x='concern_virus',顺序=['a','b','c','d','e'],
色调=年龄,色调顺序=[“年轻”,“年长”],
调色板=['Chartrese','darkviolet'])
plt.xticks(尺寸=12)
plt.xlabel(“关注级别”,大小=14)
plt.yticks(尺寸=12)
plt.ylabel('人数',大小=12)
plt.title(“老年人和年轻人对病毒的关注”,大小=16)
ax.setxticklabels(ax.getxticklabels(),rotation=40,ha=“right”)
总计=长度(df_x_1)
对于ax.patches中的p:
百分比=f'{100*p.get_height()/total:.1f}%\n'
x=p.get_x()+p.get_width()/2
y=p.获得高度()
ax.注释(百分比,(x,y),ha='center',va='center')
plt.紧_布局()
plt.show()

要使文本位于条形图的中心,请选择
ha='center'
,并将宽度的一半添加到x位置。在文本中添加换行符有助于将文本很好地放置在条的顶部
plt.tight_layout()
有助于将所有标签放入绘图中

Seaborn允许您通过
order=…
确定x轴的顺序。图例元素的顺序和相应的颜色可以通过
hue\u order=…
palete=…
设置

PS:对于新的问题,每个年龄组的总数,而不是直接循环通过所有栏,第一个循环可以访问组:

导入matplotlib.pyplot作为plt
作为pd进口熊猫
将numpy作为np导入
导入seaborn作为sns
标签_younger=‘younger’
label_older='older'
df_younger=pd.DataFrame({'concern_virus':np.random.choice(['a','b','c','d','e'],230]))
df_older=pd.DataFrame({'concern_virus':np.random.choice(['a','b','c','d','e'],120]))
df_younger['age']=标签_younger
df_older['age']=标签_older
df_x_1=pd.concat([df_younger,df_older],ignore_index=True)
plt.图(figsize=(7,5))
ax=sns.countplot(数据=df_x_1,x='concern_virus',顺序=['a','b','c','d','e'],
色调=年龄,色调顺序=[label\u younger,label\u older],
调色板=[‘橙色’、‘天蓝色’])
plt.xticks(尺寸=12)
plt.xlabel(“关注级别”,大小=14)
plt.yticks(尺寸=12)
plt.ylabel('人数',大小=12)
plt.title(“老年人和年轻人对病毒的关注”,大小=16)
ax.setxticklabels(ax.getxticklabels(),rotation=40,ha=“right”)
对于ax容器中的棒材:
如果bar.get_label()==label_:
组总=len(df_)
其他:
组总=len(df_旧)
对于条形图中的p:
#打印(p.获取面部颜色(),p.获取标签())
百分比=f'{100*p.获取高度()/组总数:.1f}%\n'
x=p.get_x()+p.get_width()/2
y=p.获得高度()
ax.注释(百分比,(x,y),ha='center',va='center')
plt.紧_布局()
plt.show()

对不起,我刚才检查了一下,百分比加起来都是100。也许我的问题不好,但我有两个组(年长组和年轻组),每个组应该增加100%,因为我合并了两个数据帧,然后创建了列年龄(年轻组/年长组)。有办法吗?我最初使用子图,有两个并排的条形图,但无法将它们恢复到likert比例顺序。再次感谢你的帮助。嗨,它现在可以工作了,但是我上面有一系列的浮动(0.384856,0.7867473,0.5848583,1.0)\没有传说这大约有10行长,我想知道如何摆脱它。你能编辑你的问题并添加你的新代码和你获得的绘图吗?seaborn会根据“年龄”列中的元素(当设置了
hue='age'
时)自动创建图例。是否收到错误消息?是否安装了seaborn(0.10.1)和matplotlib(3.3.1)的最新版本?我对seaborn和matplotlib进行了更新。