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

如何在Matlab中绘制包含离散与连续数据的混合热图?

Matlab 绘制混合离散/连续值的热图方案

核心思路

通过分离连续值与离散值图层,先绘制连续值热图,再用色块覆盖离散值对应的单元格,最后统一添加图例实现混合展示。

完整代码示例

% 1. 构造示例数据(替换成你的真实矩阵)
M = randi([20,80], 10, 10); % 生成20-80的连续值矩阵
% 随机插入离散标记值
disp_pos = randperm(numel(M), 15);
M(disp_pos(1:5)) = 100;  % 对应z
M(disp_pos(6:10)) = 700; % 对应x
M(disp_pos(11:15)) = 900;% 对应p

% 2. 绘制连续值热图基底
figure;
M_cont = M;
% 将离散值替换为NaN,避免干扰连续色阶渲染
M_cont(M_cont == 100 | M_cont == 700 | M_cont == 900) = NaN;
imagesc(M_cont);
colormap(jet); % 可替换为你需要的连续色图,如parula、viridis
colorbar('Label', 'abc [mm]');
hold on;

% 3. 为离散值绘制专属色块
% 定义离散值对应的颜色(可自行调整)
disp_color_map = [0.1 0.1 0.1;  % 100 → 深灰
                  1 0 0;        % 700 → 红色
                  0 0.8 0];     % 900 → 绿色
disp_values = [100, 700, 900];
disp_labels = {'z', 'x', 'p'}; % 对应离散值的含义标签

% 遍历每个离散值,定位并绘制色块
for idx = 1:length(disp_values)
    [rows, cols] = find(M == disp_values(idx));
    for cell_idx = 1:length(rows)
        % rectangle参数:[x起始, y起始, 宽度, 高度],适配imagesc的坐标规则
        rectangle('Position', [cols(cell_idx)-0.5, rows(cell_idx)-0.5, 1, 1], ...
                  'FaceColor', disp_color_map(idx,:), ...
                  'EdgeColor', 'white', 'LineWidth', 0.5);
    end
end

% 4. 添加统一图例
legend_handles = [];
% 连续值图例项
legend_handles(end+1) = patch('FaceColor', 'none', 'EdgeColor', 'none', ...
                              'DisplayName', '20-80 [mm]');
% 离散值图例项
for idx = 1:length(disp_values)
    legend_handles(end+1) = patch('FaceColor', disp_color_map(idx,:), ...
                                  'EdgeColor', 'k', 'DisplayName', disp_labels{idx});
end
legend(legend_handles, 'Location', 'best');
axis equal tight;
title('混合离散/连续值热图');

关键细节说明

  • 离散值必须先从连续矩阵中替换为NaN,防止连续色阶被异常值干扰
  • rectangle的位置参数需要减去0.5,才能刚好覆盖imagesc的单个单元格
  • 可自定义连续色图(如colormap(custom_map)),避免与离散色冲突
  • 如果需要更精准的单元格边框控制,可调整EdgeColor和LineWidth参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:25:09