You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Seaborn绘制的图表下方添加居中的分类统计表格

解决seaborn jointplot添加底部居中统计表格的方案

问题原因

seaborn的jointplot接口返回的是JointGrid实例,整个画布包含3个子轴:中间散点主轴、上方X变量边际分布轴、右侧Y变量边际分布轴。直接调用plt.table时,默认会绑定当前激活的右侧边际轴,因此表格会偏移到右侧无法居中。

实现步骤

  1. 先统计各分类的样本数量,整理为目标表格结构
  2. 手动在整个画布底部新增一块独立区域放置表格,避免和原有子轴冲突
  3. 调整画布底部留白,给表格预留足够显示空间
  4. 隐藏表格区域的坐标轴,仅保留表格内容

完整可运行代码

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = {'Category': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'],
        'var1': [1, 2, 2, 4, 5, 3, 4, 5, 4, 7],
        'var2': [2, 4, 8, 9, 4, 2, 3, 8, 3, 7]}
df = pd.DataFrame(data)

# 绘制jointplot,保留返回的JointGrid对象
g = sns.jointplot(data=df, x='var1', y='var2', hue='Category')
g.fig.suptitle('Example Data', y=1.02) # 调整标题位置避免遮挡

# 计算分类计数,整理为目标表格格式
cat_counts = df['Category'].value_counts().sort_index()
table_data = [['Count'] + cat_counts.values.tolist()]
table_cols = ['Category'] + cat_counts.index.tolist()

# 调整画布底部留白,给表格腾位置
plt.subplots_adjust(bottom=0.25)

# 手动添加表格区域:参数依次为[左边界位置, 下边界位置, 宽度, 高度],取值范围0-1(画布比例)
table_ax = g.fig.add_axes([0.25, 0.05, 0.5, 0.1])
# 隐藏表格区域的坐标轴
table_ax.axis('off')

# 绘制表格
table = table_ax.table(cellText=table_data,
                      colLabels=table_cols,
                      cellLoc='center',
                      loc='center',
                      bbox=[0,0,1,1])
# 调整表格字体大小避免溢出
table.auto_set_font_size(False)
table.set_fontsize(10)

plt.show()

效果说明

上述代码会在jointplot整体画布的底部居中位置生成你需要的分类计数表格,如果需要把表格放在顶部,只需修改add_axes的下边界参数即可,例如将[0.25, 0.05, 0.5, 0.1]改为[0.25, 0.9, 0.5, 0.1],同时调整subplots_adjust的top参数预留顶部空间。

内容的提问来源于stack exchange,提问作者pkpto39

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 04:24:03