multiple imagesc plot with one colorbar in matlab

8 views (last 30 days)
How should I plot 10 square size imagesc plot in matlab? All of them has same x and y limit. I want to plot in two horizontal lines in which in the first line I will plot 5 square size imagesc plot side by side and in the downward line, I will plot the rest 5 imagesc plot. I want to include one colorbar in the east side which matches the size of upper line and lower line of the plots?

Answers (1)

Aastha
Aastha on 18 Jun 2025
I understand that you want to create a layout of "imagesc" plots in MATLAB, all with the same x and y limits, and include a single colorbar on the east side that spans the full height of both rows. You can do this by following the steps below:
1. Use a loop with an index "i" ranging from 1 to 10, along with the function "subplot(2,5, i)", to create a grid of 2 rows and 5 columns containing square "imagesc" plots. Please see the MATLAB code snippet below for reference:
% Generate dummy data for visualization
[x, y] = meshgrid(0:0.1:1, 0:0.1:1);
z = rand(11, 11, 10);
minColorLimit = min(z(:));
maxColorLimit = max(z(:));
fig = figure(1);
clf;
% Define subplot grid: 2 rows × 5 columns
for i = 1:10
subplot(2, 5, i);
imagesc(x(1,:), y(:,1), z(:,:,i));
axis square;
set(gca, 'XTick', [], 'YTick', []);
end
2. To add a single colorbar that spans the entire height of both subplot rows, use the "colorbar" function. Position it on the east side by specifying its size and location using the "Position" Name-Value pair, which is an array of the form [left, bottom, width, height]. Create an invisible axes object "h" to hold the overall figure title and axis labels. This keeps them separate from individual subplots. Please refer to the following MATLAB code:
h = axes(fig, 'visible', 'off');
h.Title.Visible = 'on';
h.XLabel.Visible = 'on';
h.YLabel.Visible = 'on';
title(h, 'Title');
xlabel(h, 'x-axis');
ylabel(h, 'y-axis');
axis tight
% Create a colorbar next to the rightmost column of subplots
cb = colorbar(h, 'Position', [0.92 0.19 0.02 0.64]); % [left bottom width height]
colormap('jet');
cb.Limits = [minColorLimit, maxColorLimit];
set(gca, 'FontSize', 8);
For more information on the "subplot", "colorbar", and "imagesc" functions, you can refer to the following MathWorks documentation:
I hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!