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

如何在Holoviews中让多张热图共享坐标轴并统一网格尺寸?

统一Holoviews多张热图的网格尺寸与数据范围

要让多张热图使用相同的7×6网格并统一呈现,需要完成两个核心操作:补全缺失的网格节点(添加空单元格)和强制统一坐标轴与颜色映射范围。

1. 补全热图的网格数据

遍历目标网格的所有x(0-6)和y(0-5)坐标,将原始数据中不存在的点补充为None(Holoviews会将其渲染为空单元格):

import random
import holoviews as hv
hv.extension("matplotlib")

# 定义目标网格的固定范围
target_x = range(7)
target_y = range(6)

# 生成原始数据
data1 = [(x, y, random.random()) for x in range(3) for y in range(6)]
data2 = [(x, y, random.random() * 3) for x in range(7) for y in range(2)]

# 封装补全数据的工具函数
def fill_missing_grid_points(original_data, target_x, target_y):
    # 把原始数据转成字典,方便快速查找
    existing_points = {(x, y): val for x, y, val in original_data}
    # 遍历所有目标网格点,补全缺失值
    full_data = []
    for x in target_x:
        for y in target_y:
            full_data.append((x, y, existing_points.get((x, y), None)))
    return full_data

# 补全两个热图的数据
full_data1 = fill_missing_grid_points(data1, target_x, target_y)
full_data2 = fill_missing_grid_points(data2, target_x, target_y)

2. 统一坐标轴与颜色映射

创建热图时,用redim.range锁定x/y轴的范围,同时通过clim参数统一颜色条的数值区间(确保不同热图的颜色标尺一致):

# 创建固定尺寸的热图
hmap1 = hv.HeatMap(full_data1).redim.range(x=(0, 6), y=(0, 5))
hmap2 = hv.HeatMap(full_data2).redim.range(x=(0, 6), y=(0, 5))

# 组合热图并配置统一样式
combined = (hmap1 + hmap2).opts(
    hv.opts.HeatMap(
        show_values=False,
        colorbar=True,
        clim=(0, 3)  # 匹配data2的最大值范围,可按需调整
    )
)

combined

批量处理多张热图

如果需要处理更多热图,直接用循环批量完成数据补全和配置:

# 示例:批量处理3张热图
data3 = [(x, y, random.random() * 2) for x in range(5) for y in range(4)]
all_datasets = [data1, data2, data3]

# 批量生成统一尺寸的热图
uniform_heatmaps = []
for dataset in all_datasets:
    full_data = fill_missing_grid_points(dataset, target_x, target_y)
    hmap = hv.HeatMap(full_data).redim.range(x=(0, 6), y=(0, 5))
    uniform_heatmaps.append(hmap)

# 组合并应用统一样式
combined_batch = hv.Layout(uniform_heatmaps).opts(
    hv.opts.HeatMap(show_values=False, colorbar=True, clim=(0, 3))
)

combined_batch

关键注意点

  • 用None填充缺失点不会干扰原始数据的显示,只会补充空白网格。
  • redim.range是强制锁定坐标轴范围的有效方式,比redim.values更直接可靠。
  • clim参数可根据所有热图的整体数据范围调整,确保颜色对比的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:03:40