英文:
How do I add a percentage to a countplot?
问题
I need to show a percentage for my bar graph. However I am not sure how to do it.
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()
英文:
I need to show a percentage for my bar graph. However I am not sure how to do it.
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()
答案1
得分: 5
- 从
matplotlib v.3.4.0
开始,正确的注释条形图的方法是使用.bar_label
方法,详细说明在 如何在条形图上添加值标签 中有描述。 seaborn.countplot
返回ax : matplotlib.Axes
,因此习惯上使用ax
作为这个 axes-level 方法 的别名。Axes
是显式接口。
- 这使用了您其他的问题中的数据。
- 在
python 3.11.2
,pandas 2.0.0
,matplotlib 3.7.1
,seaborn 0.12.2
中进行了测试
ax = sns.countplot(y='type', data=df, palette='colorblind')
# 获取类型列的总计数
total = df['type'].count()
# 使用来自matplotlib v3.7.0的fmt注释条形图
ax.bar_label(ax.containers[0], fmt=lambda x: f'{(x/total)*100:0.1f}%')
# 在条形图的末尾添加标签的空间
ax.margins(x=0.1)
ax.set(xlabel='Count', ylabel='Type', title='Movie Type in Disney+')
plt.show()
- 同样的实现也适用于垂直条形图
ax = sns.countplot(x='type', data=df, palette='colorblind')
# 获取类型列的总计数
total = df['type'].count()
# 使用来自matplotlib v3.7.0的fmt注释条形图
ax.bar_label(ax.containers[0], fmt=lambda x: f'{(x/total)*100:0.1f}%')
plt.show()
v3.4.0 <= matplotlib < v3.7.0
使用labels
参数。
# 对于水平条形图
labels = [f'{(w/total)*100:0.1f}%' if (w := v.get_width()) > 0 else '' for v in ax.containers[0]]
# 对于垂直条形图
# 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)
英文:
- From
matplotlib v.3.4.0
, the correct way to annotate bars is with the.bar_label
method, as thoroughly described in How to add value labels on a bar chart seaborn.countplot
returnsax : matplotlib.Axes
, so it's customary to usax
as the alias for this axes-level method.Axes
is the explicit interface.
- This uses data from your other question.
- Tested in
python 3.11.2
,pandas 2.0.0
,matplotlib 3.7.1
,seaborn 0.12.2
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()
- The same implementation also works for vertical bars
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()
v3.4.0 <= matplotlib < v3.7.0
use thelabels
parameter.
# 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)
答案2
得分: 3
开始的代码看起来很棒!你只需通过将每个柱的宽度除以总计数并乘以100来计算每个柱的百分比值。然后使用annotate函数将你计算的这些值作为文本添加到柱上。尝试下面的代码,看看它是否适用于你!
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style('whitegrid')
# 创建countplot并将其命名为'plot'。
plot = sns.countplot(y='type', data=df, palette='colorblind')
plt.xlabel('Count')
plt.ylabel('Type')
plt.title('Movie Type in Disney+')
total = len(df['type'])
for p in plot.patches:
percentage = '{:.1f}%'.format(100 * p.get_width() / total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height() / 2
plot.annotate(percentage, (x, y))
plt.show()
英文:
The beginning code looks great! You just have to calculate the percentage values for each bar by dividing the width of the bar by the total count and multiplying by 100. Then use the annotate function to add those values you calculated as text to the bar. Try the code below and see if it works out for you!
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style('whitegrid')
# Create the countplot and naming it 'plot'.
plot = sns.countplot(y='type', data=df, palette='colorblind')
plt.xlabel('Count')
plt.ylabel('Type')
plt.title('Movie Type in Disney+')
total = len(df['type'])
for p in plot.patches:
percentage = '{:.1f}%'.format(100 * p.get_width() / total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height() / 2
plot.annotate(percentage, (x, y))
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论