In matlab, how to 'smooth' pixels in 2D heatmap using imagesc

11,135

Solution 1

interp2 may be of use here. Use the data as key points, then create a finer grid of points that span the same width and height and interpolate in between the key points.

Something like this:

%// Define your data
data = [1 1 1 1 1 1 1 1 1 1; 1 1.04 1.04 1.04 1.03 1 1.01 1.01 1.03 1.01; 1.36 1.3 1.25 1.2 1.15 1.1 1.2 1.13 1.07 1.11; 3.65 3.16 2.94 2.68 2.39 2.22 2.17 1.95 1.79 1.81; 5.91 5.75 5.47 5.3 4.98 4.79 4.62 4.55 4.38 4.19; 6 6 5.99 5.83 5.49 5.33 5.14 4.94 4.77 4.74];    

%// Define integer grid of coordinates for the above data
[X,Y] = meshgrid(1:size(data,2), 1:size(data,1));

%// Define a finer grid of points
[X2,Y2] = meshgrid(1:0.01:size(data,2), 1:0.01:size(data,1));

%// Interpolate the data and show the output
outData = interp2(X, Y, data, X2, Y2, 'linear');
imagesc(outData);

%// Cosmetic changes for the axes
set(gca, 'XTick', linspace(1,size(X2,2),size(X,2))); 
set(gca, 'YTick', linspace(1,size(X2,1),size(X,1)));
set(gca, 'XTickLabel', 1:size(X,2));
set(gca, 'YTickLabel', 1:size(X,1));

%// Add colour bar
colorbar;

The code that's at the bottom is required because defining the finer grid ultimately increases the size of the image. I need to relabel the axes to go back to the original size.

We get this:

enter image description here

Small Note

I'm using MATLAB R2014a, and the default colour map is jet. You're using R2014b+ and the default colour map is parula. You won't get the same colour distribution as me, but you will get the smoothness you desire.

Solution 2

You can also use the pcolor(data) function with shading interp to make the color resolution smooth. No need to interpolate the data before plotting.

Share:
11,135
user2861089
Author by

user2861089

Updated on June 17, 2022

Comments

  • user2861089
    user2861089 almost 2 years

    Using MATLAB, I have a matrix (data) and am plotting using imagesc(data) to produce a heatmap:

    data = [1 1 1 1 1 1 1 1 1 1; 1 1.04 1.04 1.04 1.03 1 1.01 1.01 1.03 1.01; 1.36 1.3 1.25 1.2 1.15 1.1 1.2 1.13 1.07 1.11; 3.65 3.16 2.94 2.68 2.39 2.22 2.17 1.95 1.79 1.81; 5.91 5.75 5.47 5.3 4.98 4.79 4.62 4.55 4.38 4.19; 6 6 5.99 5.83 5.49 5.33 5.14 4.94 4.77 4.74];
    imagesc(data)
    

    enter image description here

    Is there a way to 'smooth' the pixels in order to produce something more like this: enter image description here