MATLAB: How to generate a 2D grid plot the data

heatmapMATLAB

I have X, Y and Z vectors where X and Y correspond to the x, y co-ordinates and Z is the value at that point. I want to generate a plot in which the elements of a matrix 'Z' are represented by colored squares in a 2-D grid. The color of a square in the grid is determined by the Z value of the square. I want to specify my own colormap for the plot.

Best Answer

You can use the PCOLOR function to plot a pseudocolor (checkerboard) plot. The plot is a logically rectangular, two-dimensional grid with vertices at the points [X(i,j), Y(i,j)] where, X and Y are vectors or matrices that specify the spacing of the grid lines. Increase the size of data (Z) and X, Y co-ordinates by one if you want the number of squares to be the size of the data.
%Generate the X and Y grid arrays using the MESHGRID function.
x = [1:6];
y = [1:4];
[X,Y] = meshgrid(x,y)
%Note that size(Z) is the same as size(x) and size(y)
Z = [1 0 -2 1 2 1;2 -2 0 -1 0 1;1 0 0 -2 2 1;1 1 1 1 1 1];
% create a colormap having RGB values of dark green,
%light green, white, dark red and light red.
map2 = [0 1 0; 0 0.8 0;1 1 1;0.6 0 0;1 0 0 ];
%use the user defined colormap for figure.
colormap(map2);
%plot the figure
pcolor(X,Y,Z);
%set the x and y labels
set(gca,'XTick',[1 2 3 4 5 6],'YTick',[1 2 3 4],'XTicklabel',[' ';'a';'b'; 'c'; 'd';'e'],'YTicklabel',[' ';'f';'g';'h']);
%set the color limits
caxis([-2 2])