如何在Seaborn/Matplotlib柱状图上显示条形的Y轴数值?
在Seaborn Countplot条形上显示Y轴数值的几种方法
刚好我也经常碰到这个需求,下面给你分享几个靠谱的实现方式,结合你的代码来一步步说明:
方法1:遍历条形补丁(最通用,适配所有版本)
Seaborn的countplot返回的是Matplotlib的Axes对象,我们可以直接遍历这个对象里的所有条形(patches),然后用plt.text在每个条形的合适位置标注数值。
完整代码示例:
import matplotlib.pyplot as plt import seaborn as sns # 你的原有代码,先获取Axes对象 plt.figure(figsize=(10,5)) ax = sns.countplot(x='subject', data=udemy, hue='is_paid') # 遍历每个条形补丁 for patch in ax.patches: # 获取条形的高度(即计数数值) height = patch.get_height() # 如果高度为0,跳过(避免显示0标签) if height == 0: continue # 在条形上方居中位置添加数值标签 ax.text( patch.get_x() + patch.get_width() / 2, # X坐标:条形中心 height, # Y坐标:条形顶端 int(height), # 显示的数值(转成整数更美观) ha='center', # 水平居中 va='bottom', # 垂直对齐在条形顶端下方 fontsize=10 ) plt.show()
方法2:使用Matplotlib的bar_label(简洁高效,Matplotlib 3.4+可用)
从Matplotlib 3.4版本开始,新增了bar_label方法,可以直接给条形容器添加标签,比手动遍历更简洁。因为你用了hue,所以图里会有两个条形容器(对应is_paid的两个类别),我们需要分别给它们加标签。
代码示例:
import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(10,5)) ax = sns.countplot(x='subject', data=udemy, hue='is_paid') # 给每个条形容器添加标签 for container in ax.containers: ax.bar_label(container, label_type='edge') # label_type='edge'表示标签在条形顶端 plt.show()
如果想让标签在条形内部,可以把label_type改成'center',还能通过fmt参数格式化数值,比如fmt='%d'强制显示整数。
方法3:手动统计数据后绘制(灵活可控)
如果需要更精细的控制,我们可以先自己统计每个类别的频数,再用Seaborn的barplot绘制,同时添加标签。这种方式适合需要对数据先做预处理的场景。
代码示例:
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # 先统计每个subject和is_paid组合的计数 count_data = udemy.groupby(['subject', 'is_paid']).size().unstack() plt.figure(figsize=(10,5)) ax = sns.barplot(data=count_data) # 遍历每个条形添加标签 for i, subject in enumerate(count_data.index): for j, is_paid in enumerate(count_data.columns): count = count_data.loc[subject, is_paid] if count > 0: # 计算标签位置:每个条形的中心X坐标,Y坐标为计数 x = i - 0.2 + j*0.4 # 适配hue并排条形的X偏移 ax.text(x, count, int(count), ha='center', va='bottom') plt.show()
小提示:
- 如果条形高度差异很大,矮条形的标签可能重叠,可以设置
va='top'把标签放在条形内部,或者调小字体大小。 - 可以用
plt.ylim()适当扩大Y轴范围,避免顶部标签被切掉,比如plt.ylim(0, max_count * 1.1),其中max_count是数据里的最大计数值。
内容的提问来源于stack exchange,提问作者Maitrik1998
相关产品推荐
相关产品推荐

