可以通过以下步骤解决:
import seaborn as sns
import matplotlib.pyplot as plt
# 导入数据集
data = sns.load_dataset('tips')
sns.countplot(x='day', data=data)
# 计算每个类别的百分比
total = len(data['day'])
counts = data['day'].value_counts()
percentages = [(count/total)*100 for count in counts]
# 在条形图顶部添加百分比标签
for i, p in enumerate(ax.patches):
x = p.get_x() + p.get_width() / 2
y = p.get_height()
ax.annotate(f'{percentages[i]:.1f}%', (x, y), ha='center', va='bottom')
完整的代码示例:
import seaborn as sns
import matplotlib.pyplot as plt
# 导入数据集
data = sns.load_dataset('tips')
# 绘制countplot
ax = sns.countplot(x='day', data=data)
# 计算每个类别的百分比
total = len(data['day'])
counts = data['day'].value_counts()
percentages = [(count/total)*100 for count in counts]
# 在条形图顶部添加百分比标签
for i, p in enumerate(ax.patches):
x = p.get_x() + p.get_width() / 2
y = p.get_height()
ax.annotate(f'{percentages[i]:.1f}%', (x, y), ha='center', va='bottom')
# 显示图形
plt.show()
这样就可以在seaborn countplot的条形图顶部添加百分比标签了。
领取专属 10元无门槛券
手把手带您无忧上云