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

如何让Seaborn heatmap的x轴按测量值实际间隔正确排布?

实现方案

seaborn.heatmap 本质是面向分类坐标轴的可视化接口,所有列/行都会被视为离散分类,默认按等间距渲染,无法直接满足数值型x轴的比例间距需求,推荐改用matplotlib的pcolormesh接口实现,具体代码如下:

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

# 原始数据
df = pd.DataFrame(np.random.randint(0,2,size=(5, 8)), columns=[1,1.1,2,3,4,1001,1002,1003], index=['A','B','C','D','E'])

# 步骤1:补全时间序列,缺失时间点填充0
# 取时间列的最小间隔作为重采样步长
time_col = df.columns.astype(float)
min_step = np.min(np.diff(time_col))
# 生成完整的时间序列
full_time = np.arange(time_col.min(), time_col.max() + min_step, min_step)
# 重索引补全缺失值,默认填0
df_full = df.reindex(columns=full_time, fill_value=0)

# 步骤2:用pcolormesh绘制比例间距热图
y = np.arange(df_full.shape[0]+1)
x = full_time
fig, ax = plt.subplots(figsize=(12, 4))
# 绘制热力图,cmap用binary对应0黑1白
pcm = ax.pcolormesh(x, y, df_full.values, cmap='binary', vmin=0, vmax=1)

# 步骤3:调整坐标轴样式
ax.set_yticks(np.arange(0.5, len(df.index), 1))
ax.set_yticklabels(df.index)
ax.set_xlabel('时间')
ax.set_ylabel('点位')
# 添加色卡
plt.colorbar(pcm, ticks=[0,1], label='是否完成测量')

plt.tight_layout()
plt.show()

效果说明

  • 代码会自动根据原始时间列的最小间隔生成完整时间轴,所有未出现在原数据中的时间点都会自动填充为0
  • x轴间距完全和时间的数值差成正比,1到1.1的间距仅为1001到1002间距的1/10,1到1001的间距会远大于相邻小时间差的间距
  • 如果需要调整时间轴的精度,可以自行修改min_step的取值,不需要完全和原始数据的最小间隔一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:09:02