如何为分组条形图标注分组计数而非条形高度?
修改Seaborn分组条形图标注为分组计数
你需要将原代码中基于小费均值的标注,改为每组数据的出现频次,这里提供两种可行方案:
方案一:使用countplot自动统计频次
countplot是Seaborn专门用于统计分类数据频次的图表,会自动计算每个x+hue组合的样本数量,无需额外统计:
import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="whitegrid") df = sns.load_dataset("tips") # 用countplot直接统计每天不同性别的人数 ax = sns.countplot(x='day', hue="sex", data=df, palette="tab20_r") # 遍历每个条形,标注对应的频次 for rect in ax.patches: y_value = rect.get_height() # countplot的条形高度就是频次 x_value = rect.get_x() + rect.get_width() / 2 space = 1 label = f"{int(y_value)}" # 直接取整数频次作为标注文本 ax.annotate(label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center', va='bottom') plt.show()
方案二:手动统计分组计数后绘图
如果需要更灵活的统计逻辑(比如后续要扩展其他计算),可以先手动分组统计频次,再用barplot绘制:
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd sns.set_theme(style="whitegrid") df = sns.load_dataset("tips") # 手动统计每天每个性别的人数,生成新的统计DataFrame count_df = df.groupby(['day', 'sex']).size().reset_index(name='count') # 基于统计后的count列绘制条形图 ax = sns.barplot(x='day', y='count', hue="sex", data=count_df, palette="tab20_r") # 标注每组的频次 for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = 1 label = f"{int(y_value)}" ax.annotate(label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center', va='bottom') plt.show()
内容的提问来源于stack exchange,提问作者user20566115
相关产品推荐
相关产品推荐

