Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: How to align the axes of subplots when one of them contains a colorbar?

Tags:

plot

axes

matlab

Minimal example:

[x,y,z] = peaks(50);
figure;
subplot(5,1,1:4);
pcolor(x,y,z);
shading flat;
colorbar;
subplot(5,1,5);
plot(x(end/2,:), z(end/2,:));

output

In this example I'd like to have the lower subplot show the cross-section of peaks along y=0 and the plot ending at the same position as the pcolor subplot, so that the x ticks are on identical positions. In fact, I don't need the duplicate x axis then. So,

How to rescale the lower subplot such that the right limit matches the right limit of the upper one's plot part? (preferably such that the colorbar can be switched on/off without destroying that alignment)

(FYI I learned I can use the linkaxes command then to have a correct zoom behaviour in a second step)

like image 643
Tobias Kienzler Avatar asked Mar 10 '11 12:03

Tobias Kienzler


People also ask

How do I move the position bar color in Matlab?

To move the colorbar to a different tile, set the Layout property of the colorbar. To display the colorbar in a location that does not appear in the table, use the Position property to specify a custom location. If you set the Position property, then MATLAB sets the Location property to 'manual' .

How can you plot subplots with different sizes in Matlab?

It's possible to make subplots of different sizes by specifying a multiple-element vector for the grid position argument p in the syntax subplot(m,n,p) .

How are subplots counted in Matlab?

The subplots are numbered starting from top row left to right then along the second row and so on. For example: The following commands: subplot(2,1,1); plot (profit); subplot(2,1,2); plot (loss);

How do you split a subplot in Matlab?

subplot( m , n , p ) divides the current figure into an m -by- n grid and creates axes in the position specified by p . MATLAB® numbers subplot positions by row. The first subplot is the first column of the first row, the second subplot is the second column of the first row, and so on.


1 Answers

You can just set the width of the second subplot to the width of the first by changing the Position property.

[x,y,z] = peaks(50);
figure;
ah1 = subplot(5,1,1:4); %# capture handle of first axes
pcolor(x,y,z);
shading flat;
colorbar;
ah2 = subplot(5,1,5); %# capture handle of second axes
plot(x(end/2,:), z(end/2,:));

%# find current position [x,y,width,height]
pos2 = get(ah2,'Position');
pos1 = get(ah1,'Position');

%# set width of second axes equal to first
pos2(3) = pos1(3);
set(ah2,'Position',pos2)

You can then further manipulate your axes properties, for example you can turn of the x-labels on the first plot, and move the second one up so that they touch:

set(ah1,'XTickLabel','')
pos2(2) = pos1(2) - pos2(4);
set(ah2,'Position',pos2)

enter image description here

like image 152
Jonas Avatar answered Sep 20 '22 13:09

Jonas