您可以通过几种不同的方式将分散或稀疏的矩阵数据转换为热图,从而提供更好的点密度可视化。我将在此处展示的示例将从分散数据开始,因此如果您已经有二维矩阵/直方图中的数据,则可以跳过初始步骤...
直方图:
如果您的分散数据相当密集,那么您可能只需要一个简单的 2D 直方图。您可以创建一个覆盖散点的网格(以您选择的分辨率)并使用 histcounts2 在 x 和 y 方向对数据进行分类:
% Normally distributed sample points:
x = randn(1, 10000);
y = randn(1, 10000);
% Bin the data:
pts = linspace(-4, 4, 101);
N = histcounts2(y(:), x(:), pts, pts);
% Plot scattered data (for comparison):
subplot(1, 2, 1);
scatter(x, y, 'r.');
axis equal;
set(gca, 'XLim', pts([1 end]), 'YLim', pts([1 end]));
% Plot heatmap:
subplot(1, 2, 2);
imagesc(pts, pts, N);
axis equal;
set(gca, 'XLim', pts([1 end]), 'YLim', pts([1 end]), 'YDir', 'normal');
这是结果图:
直方图+过滤:
如果您的分散数据相当稀疏,您仍然可以像上面一样创建直方图,但然后过滤结果以使其平滑。如果你有Image Processing Toolbox,你可以使用imdilate,或者创建一个过滤矩阵并使用conv2。这是后者的一个例子:
% Normally distributed sample points:
x = randn(1, 100);
y = randn(1, 100);
% Bin the data:
pts = linspace(-3, 3, 101);
N = histcounts2(y(:), x(:), pts, pts);
% Create Gaussian filter matrix:
[xG, yG] = meshgrid(-5:5);
sigma = 2.5;
g = exp(-xG.^2./(2.*sigma.^2)-yG.^2./(2.*sigma.^2));
g = g./sum(g(:));
% Plot scattered data (for comparison):
subplot(1, 2, 1);
scatter(x, y, 'r.');
axis equal;
set(gca, 'XLim', pts([1 end]), 'YLim', pts([1 end]));
% Plot heatmap:
subplot(1, 2, 2);
imagesc(pts, pts, conv2(N, g, 'same'));
axis equal;
set(gca, 'XLim', pts([1 end]), 'YLim', pts([1 end]), 'YDir', 'normal');
这是结果图:
距离变换:
从上面的稀疏直方图开始,您可以使用Image Processing Toolbox 中的bwdist 创建数据的距离变换。这将根据每个像素与最近的非零像素的距离为每个像素分配一个值。
或者,您可以避免通过creating a grid 覆盖您的散点并使用Statistics Toolbox 中的pdist2 计算从每个网格点到您的散点之一的最小距离来计算二维直方图。这是一个示例(使用与上面相同的示例数据):
% Generate grid and compute minimum distance:
pts = linspace(-3, 3, 101);
[X, Y] = meshgrid(pts);
D = pdist2([x(:) y(:)], [X(:) Y(:)], 'euclidean', 'Smallest', 1);
% Plot scattered data:
subplot(1, 2, 1);
scatter(x, y, 'r.');
axis equal;
set(gca, 'XLim', pts([1 end]), 'YLim', pts([1 end]));
% Plot heatmap:
subplot(1, 2, 2);
imagesc(pts, pts, reshape(D, size(X)));
axis equal;
set(gca, 'XLim', pts([1 end]), 'YLim', pts([1 end]), 'YDir', 'normal');
colormap(flip(parula(), 1));
这是结果图: