Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: Stacking of various plots

Tags:

plot

matlab

I have a question regarding the following graph:

enter image description here Essentially, we have here two subplots that have the same x-axis. I would like to save space now, and instead of having 2 subplots with two x-axix labels, I would like to eleminiate the space between them and stack them on top of each other.

Is there any easy way to do that?

Many thanks! Patrick

%% Data
t  = 0:100;
f1 = 0.3;
f2 = 0.07;
u1 = sin(f1*t);   cu1 = 'r'; %red
u2 = cos(f2*t);   cu2 = 'b'; %blue
v1 = 5*u1.^2;     cv1 = 'm'; %magenta
v2 = 5*u2.^2;     cv2 = 'c'; %cyan

figure;
h(1) = subplot(2,1,1); % upper plot
plot(t,u1,'Color',cu1,'DisplayName','u1'); hold on;
plot(t,u2,'Color',cu2,'DisplayName','u2'); hold off;

xlabel('Time t [s]');
ylabel('u [some unit]');
legend(gca,'show');

h(2) = subplot(2,1,2); % lower plot
plot(t,v1,'Color',cv1,'DisplayName','v1'); hold on;
plot(t,v2,'Color',cv2,'DisplayName','v2'); hold off;

xlabel('Time t [s]');
ylabel('v [some unit^2]');
legend('show');

linkaxes(h,'x'); % link the axes in x direction (just for convenience)
like image 655
Patrick Avatar asked Aug 01 '12 11:08

Patrick


People also ask

Is it possible to plot multiple plots in Matlab?

By default, new plots clear existing plots and reset axes properties, such as the title. However, you can use the hold on command to combine multiple plots in the same axes. For example, plot two lines and a scatter plot.

What is a stacked plot?

stackedplot( tbl ) plots the variables of a table or timetable in a stacked plot, up to a maximum of 25 variables. The function plots the variables in separate y-axes, stacked vertically. The variables share a common x-axis. If tbl is a table, then the function plots the variables against row numbers.

Which command would you use to plot in the middle of 3 vertical subplots?

Use subplot command to make 3+ Vertically Stacked Plots.


1 Answers

Remove the xticks of the upper plot:

set(h(1),'xticklabel',[]);

and also remove the xlabel (delete or comment that line in your code)

Now move the two closer together by changing their position:

pos=get(h,'position');
bottom=pos{2}(2);
top=pos{1}(2)+pos{1}(4);
plotspace=top-bottom;
pos{2}(4)=plotspace/2;
pos{1}(4)=plotspace/2;
pos{1}(2)=bottom+plotspace/2;

set(h(1),'position',pos{1});
set(h(2),'position',pos{2});

then you'll get

enter image description here

The y-axis labels are starting to overlap, so you might also want to adjust these with

set(h(1),'ytick',[-0.5 0 0.5]);

for example, or place one y-axis at the right side with:

set(h(2),'YAxisLocation','right')
like image 57
Gunther Struyf Avatar answered Oct 16 '22 21:10

Gunther Struyf