MATLAB Answers

How to plot three subplots on the same axis?

34 views (last 30 days)
Noor Bano
Noor Bano on 27 Sep 2021 at 7:56
Commented: Noor Bano on 27 Sep 2021 at 13:50
if true
% figure(1)
x1=subplot(2,1,1);
stairs(DDr.Var1,DDr.Var2);
legend('Station 1 LHS')
ylabel('Cycle time')
title('Station 1 RHS & LHS hourly mean cycle time')
set(gca,'XTickLabel',[]);
ylim([0 105]);
x2=subplot(2,1,2);
stairs(DDr.Var1,DDr.Var3);
ylabel('Cycle time')
legend(' Station 1 RHS')
ylim([0 105]);
p1 = get(x1, 'Position');
p2 = get(x2, 'Position');
p1(2) = p2(2)+p2(4);
set(x1, 'pos', p1);
xlabel('Time')
end
I found the above code for two subplot on the same axis,
I want to plot three subplots on the same x-axis without any gap between them.
I have made the following changes
if true
% figure(1)
x1=subplot(3,1,1);
stairs(DDr.Var1,DDr.Var2);
legend('Station 1 LHS')
ylabel('Cycle time')
title('Station 1 RHS & LHS hourly mean cycle time')
set(gca,'XTickLabel',[]);
ylim([0 105]);
x2=subplot(3,1,2);
stairs(DDr.Var1,DDr.Var3);
ylabel('Cycle time')
legend(' Station 1 RHS')
ylim([0 105]);
x3=subplot(3,1,3);
stairs(DDr.Var1,DDr.Var3);
ylabel('Cycle time')
legend(' Station 1 RHS')
ylim([0 105]);
Now I want to know how to change the below ?
p1 = get(x1, 'Position');
p2 = get(x2, 'Position');
p1(2) = p2(2)+p2(4);
set(x1, 'pos', p1);
xlabel('Time')
end

Accepted Answer

Dave B
Dave B on 27 Sep 2021 at 12:46
Edited: Dave B on 27 Sep 2021 at 12:47
There are a few options better than subplot.
  • The easiest thing (as @Mathieu NOE mentions in the comments) is to use stackedplot which was meant for exactly this kind of problem.
  • If you have some plotting requirements that stackedplot can't handle, tiledlayout makes this kind of problem much easier, because you can just set the TileSpacing property as you like.
  • Finally, if you need to keep using subplot (e.g. if you're on an old release) you can just set the middle axes based on the bottom one, and the top based on the middle.
Here are examples of all three:
Option 1: Use stackedplot
x=linspace(0,2*pi,100)';
y1=sin(x);
y2=cos(x);
y3=tan(x);
stackedplot(x,[y1 y2 y3])
Option 2: Use tiledlayout
figure;
t=tiledlayout(3,1,'TileSpacing','none');
nexttile;
plot(x,y1);
xticks([])
nexttile;
plot(x,y2);
xticks([])
nexttile;
plot(x,y3);
linkaxes(t.Children,'x')
Option 3: Keep using subplot:
figure;
ax1=subplot(3,1,1);
plot(x,y1);
xticks([])
ax2=subplot(3,1,2);
plot(x,y2);
xticks([])
ax3=subplot(3,1,3);
plot(x,y3);
ax2.Position(2)=ax3.Position(2)+ax3.Position(4);
ax1.Position(2)=ax2.Position(2)+ax2.Position(4);
linkaxes([ax1 ax2 ax3],'x')
  1 Comment
Noor Bano
Noor Bano on 27 Sep 2021 at 13:44
@Dave B thank you very much for such a brief explanation.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by