如何在Seaborn条形图底部添加分组统计注释?
在Seaborn条形图底部添加分组统计注释的实现方法
Seaborn基于Matplotlib开发,直接用Matplotlib的文本工具就能在图表底部添加指定注释,以下是具体实现步骤:
核心实现代码
假设你已有Seaborn条形图的绘制代码,只需在绘图完成后、plt.show()之前插入以下代码片段:
import matplotlib.pyplot as plt # 定义注释文本 annotation_text = "注:Baseline: high - 6, low - 10, medium - 6;Endline: high - 8, low - 8, medium - 6" # 获取当前坐标轴对象 ax = plt.gca() # 在图表底部居中位置添加注释 ax.text( x=0.5, y=-0.3, s=annotation_text, ha='center', # 水平居中对齐 va='top', # 垂直顶部对齐 transform=ax.transAxes, # 使用坐标轴相对坐标,适配不同图表尺寸 fontsize=10 ) # 调整底部边距,避免注释被截断(可根据注释长度调整bottom值) plt.subplots_adjust(bottom=0.2)
完整可运行示例
如果需要包含绘图逻辑的完整代码,参考以下示例:
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 示例数据集(替换为你的实际数据) df = pd.DataFrame({ 'survey': ['Baseline']*3 + ['Endline']*3, 'level': ['high', 'low', 'medium']*2, 'count': [6, 10, 6, 8, 8, 6] }) # 绘制Seaborn分组条形图 sns.barplot(x='survey', y='count', hue='level', data=df) plt.title('Survey & Level Statistics') plt.ylabel('Count') # 添加底部注释 annotation_text = "注:Baseline: high - 6, low - 10, medium - 6;Endline: high - 8, low - 8, medium - 6" ax = plt.gca() ax.text(0.5, -0.3, annotation_text, ha='center', va='top', transform=ax.transAxes, fontsize=10) plt.subplots_adjust(bottom=0.2) plt.show()
关键参数说明
transform=ax.transAxes:使用坐标轴的相对坐标(0-1范围),无论图表数据范围如何,注释都会固定在底部居中位置,避免数据坐标偏移问题。y=-0.3:控制注释在图表主体下方的距离,数值越小(更负),注释位置越靠下。plt.subplots_adjust(bottom=0.2):调整图表底部空白区域,确保注释不会被画布边缘截断,注释较长时可将bottom值调至0.25或更高。
内容的提问来源于stack exchange,提问作者Stephen Okiya
相关产品推荐
相关产品推荐

