如何向计数图中添加百分比?

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)

在此输入图像描述

Tre*_*ney 5

ax = 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)