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

如何在Seaborn heatmap(热力图)边缘添加行与列的统计数值

Seaborn热力图添加边缘行列统计值实现方案

可以实现你要的效果,核心是通过matplotlib的GridSpec布局拆分画布,分别绘制热力图、行均值横向条形图、列均值纵向条形图即可,参考效果如下:
参考效果图

实现逻辑

  • 第一步:构造或读取热力图原始数据,分别计算行维度(对应月份)的均值、列维度(对应年份)的均值
  • 第二步:使用matplotlib.gridspec.GridSpec定义画布布局,预留热力图、行统计、列统计的绘图区域,通过宽度/高度比例控制各区域大小,避免统计区域占比不合理
  • 第三步:主区域绘制Seaborn热力图,右侧区域绘制横向条形图展示行均值,底部区域绘制纵向条形图展示列均值
  • 第四步:通过共享轴的方式对齐三个绘图区域的刻度,隐藏多余的轴标签,保证分类标签和热力图完全对应

完整可运行代码示例

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import pandas as pd
import numpy as np

# 1. 构造测试数据:年份2018-2022,月份1-12,也可以替换为自己的业务数据
np.random.seed(42)
years = [2018,2019,2020,2021,2022]
months = [f'{i}月' for i in range(1,13)]
data = pd.DataFrame(np.random.randint(0,100,size=(12,5)), index=months, columns=years)

# 2. 计算行列维度统计值,如需其他统计量(求和、中位数等)替换对应计算逻辑即可
row_mean = data.mean(axis=1) # 每行(月份)的均值
col_mean = data.mean(axis=0) # 每列(年份)的均值

# 3. 定义画布布局,可调整figsize、宽高比例适配自己的需求
fig = plt.figure(figsize=(8,10))
gs = GridSpec(2,2, width_ratios=[9,1], height_ratios=[9,1], wspace=0.05, hspace=0.05)

# 4. 绘制主区域热力图
ax_heatmap = fig.add_subplot(gs[0,0])
sns.heatmap(data, ax=ax_heatmap, cmap='Blues', cbar=False)
ax_heatmap.set_xlabel('年份')
ax_heatmap.set_ylabel('月份')

# 5. 右侧绘制行均值横向条形图,共享y轴保证和热力图对齐
ax_row = fig.add_subplot(gs[0,1], sharey=ax_heatmap)
sns.barplot(x=row_mean, y=row_mean.index, ax=ax_row, color='lightblue')
# 隐藏多余的y轴标签,避免重复
ax_row.set_yticklabels([])
ax_row.set_ylabel('')
ax_row.set_xlabel('行均值')

# 6. 底部绘制列均值纵向条形图,共享x轴保证和热力图对齐
ax_col = fig.add_subplot(gs[1,0], sharex=ax_heatmap)
sns.barplot(x=col_mean.index, y=col_mean, ax=ax_col, color='lightblue')
# 隐藏多余的x轴标签,避免重复
ax_col.set_xticklabels([])
ax_col.set_xlabel('')
ax_col.set_ylabel('列均值')

plt.show()

自定义调整说明

你可以根据自己的需求修改以下配置:

  • 统计量:将计算mean的逻辑替换为sum(求和)、median(中位数)等即可展示其他统计结果
  • 样式:修改热力图的cmap参数、条形图的color参数调整配色,也可以给条形图添加数值标签
  • 布局:调整GridSpec的width_ratios、height_ratios、wspace、hspace参数修改各区域占比和间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:42:04