heatmap with categorical and quantitative color scales in matlab

Here is an example code to create a heatmap with categorical and quantitative color scales using MATLAB:

main.m
% Creating the data to plot
data = randi([1, 4], 5, 10);
categories = ["cat1", "cat2", "cat3", "cat4"];
quantiles = quantile(data(:), [0.25,0.5,0.75]);

% Plotting the heatmap
figure;
imagesc(data);
colormap([1 1 1; 0 0 1; 0 1 0; 1 1 0; 1 0 0]); % Color scale for categories
caxis([min(quantiles)-0.1 max(quantiles)+0.1]); % Setting color axis limits
colorbar;
xticklabels(1:size(data, 2));
yticklabels(categories);
xlabel("X-axis label");
ylabel("Y-axis label");

% Adding text annotations
for i = 1:size(data, 1)
    for j = 1:size(data, 2)
        text(j, i, num2str(data(i, j)), ...
             'HorizontalAlignment', 'center', ...
             'VerticalAlignment', 'middle');
    end
end
694 chars
25 lines

In this example code, data is the matrix storing the data to be plotted, categories is an array of category labels corresponding to the rows of data, quantiles are the quartiles of data, which will be used to set the limits of the color axis.

The colormap in this example uses 5 colors to represent each of the 4 categories and a white color for missing values. The caxis function is used to set the limits of the color scale to be slightly larger than the minimum and maximum values of data. The colorbar function adds a color scale legend to the plot. The xticklabels and yticklabels functions add labels to the x and y axes respectively. Finally, the for loop is used to add text annotations to each data point in the heatmap.

This will result in a heatmap with a categorical color scale for the rows of data, and a quantitative color scale for the actual data values.

related categories

gistlibby LogSnag