python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Matlab使用HeatMap画热图

Matlab之使用HeatMap实现画热图

作者:show-er-打怪之路

这篇文章主要介绍了Matlab之使用HeatMap实现画热图方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Matlab使用HeatMap画热图

注意:HeatMap和heatmap是不一样的!

使用HeatMap画热图:

clc; 
clear; 
data = [0,40,0,31,0,0,0,0;    
       30,0,40,0,2,0,1,0;       
       0,0,0,0,0,13,0,60;       
       39,0,31,0,1,0,0,0;        
       0,30,0,39,0,1,0,0;        
      1,0,1,0,56,0,12,0;       
      0,2,0,1,0,56,0,12;       
      0,0,0,0,12,0,59,0];
 xvalues = {'CNC1','CNC2','CNC3','CNC4','CNC5','CNC6','CNC7','CNC8'}; 
yvalues = {'CNC1','CNC2','CNC3','CNC4','CNC5','CNC6','CNC7','CNC8'}; 
yvalues=yvalues';
h=HeatMap(data,'Colormap',redbluecmap,'ColumnLabels',yvalues,'RowLabels',xvalues); 
h.Annotate = true;%在热图中显示数据值
 

颜色条可以使用GUI的界面插入colorbar

一个简单的matlab用画2D热图/分布图的方法

网上找到的画热图的方法大部分跟我预期都有差距,最后找到了一个代码,然后经过改良可以用来画热图/分布图。

这个代码主要是用到通过hist3这个函数对数据进行分类,然后用scatter函数进行绘制。

以随机生成x和y成正态分布均值为0,方差为10的图为例

X=normrnd(0,10,[100000,1]);
Y=normrnd(0,10,[100000,1]);
numbins = 50;
markersize = 50;
marker = '.';
[values, centers] = hist3([X Y], [numbins numbins]);
centers_X = centers{1,1};
centers_Y = centers{1,2};
binsize_X = abs(centers_X(2) - centers_X(1)) / 2;
binsize_Y = abs(centers_Y(2) - centers_Y(1)) / 2;
bins_X = zeros(numbins, 2);
bins_Y = zeros(numbins, 2);
for i = 1:numbins
	bins_X(i, 1) = centers_X(i) - binsize_X;
	bins_X(i, 2) = centers_X(i) + binsize_X;
	bins_Y(i, 1) = centers_Y(i) - binsize_Y;
	bins_Y(i, 2) = centers_Y(i) + binsize_Y;
end
scatter_COL = zeros(length(X), 1);
onepercent = round(length(X) / 100);       
for i = 1:length(X)
        last_lower_X = NaN;
        last_higher_X = NaN;
        id_X = NaN;
        c_X = X(i);
        last_lower_X = find(c_X >= bins_X(:,1));
        if (~isempty(last_lower_X))
            last_lower_X = last_lower_X(end);
        else
            last_higher_X = find(c_X <= bins_X(:,2));
            if (~isempty(last_higher_X))
                last_higher_X = last_higher_X(1);
            end
        end
        if (~isnan(last_lower_X))
            id_X = last_lower_X;
        else
            if (~isnan(last_higher_X))
                id_X = last_higher_X;
            end
        end
        last_lower_Y = NaN;
        last_higher_Y = NaN;
        id_Y = NaN;
        c_Y = Y(i);
        last_lower_Y = find(c_Y >= bins_Y(:,1));
        if (~isempty(last_lower_Y))
            last_lower_Y = last_lower_Y(end);
        else
            last_higher_Y = find(c_Y <= bins_Y(:,2));
            if (~isempty(last_higher_Y))
                last_higher_Y = last_higher_Y(1);
            end
        end
        if (~isnan(last_lower_Y))
            id_Y = last_lower_Y;
        else
            if (~isnan(last_higher_Y))
                id_Y = last_higher_Y;
            end
        end
        scatter_COL(i) = values(id_X, id_Y);
end   
scatter(X, Y, markersize, scatter_COL, marker);
hold on
colorbar;
box on

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文