Eye*_*lum 0 python matplotlib seaborn plot-annotations countplot
我需要显示条形图的百分比。但是我不知道该怎么做。
sns.set_style('whitegrid')
sns.countplot(y='type',data=df,palette='colorblind')
plt.xlabel('Count')
plt.ylabel('Type')
plt.title('Movie Type in Disney+')
plt.show()
Run Code Online (Sandbox Code Playgroud)
matplotlib v.3.4.0,注释条形图的正确方法是使用.bar_label方法,如如何在条形图上添加值标签中详细描述的seaborn.countplotreturns ax : matplotlib.Axes,因此我们习惯将其作为此轴级方法的ax别名。
Axes是显式接口。python 3.11.2, pandas 2.0.0, matplotlib 3.7.1,seaborn 0.12.2ax = sns.countplot(y='type', data=df, palette='colorblind')
# get the total count of the type column
total = df['type'].count()
# annotate the bars with fmt from matplotlib v3.7.0
ax.bar_label(ax.containers[0], fmt=lambda x: f'{(x/total)*100:0.1f}%')
# add space at the end of the bar for the labels
ax.margins(x=0.1)
ax.set(xlabel='Count', ylabel='Type', title='Movie Type in Disney+')
plt.show()
Run Code Online (Sandbox Code Playgroud)
ax = sns.countplot(x='type', data=df, palette='colorblind')
# get the total count of the type column
total = df['type'].count()
# annotate the bars with fmt from matplotlib v3.7.0
ax.bar_label(ax.containers[0], fmt=lambda x: f'{(x/total)*100:0.1f}%')
plt.show()
Run Code Online (Sandbox Code Playgroud)
v3.4.0 <= matplotlib < v3.7.0使用labels参数。# for horizontal bars
labels = [f'{(w/total)*100:0.1f}%' if (w := v.get_width()) > 0 else '' for v in ax.containers[0]]
# for vertical bars
# labels = [f'{(h/total)*100:0.1f}%' if (h := v.get_height()) > 0 else '' for v in ax.containers[0]]
ax.bar_label(ax.containers[0], labels=labels)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1186 次 |
| 最近记录: |