Merge two plots with the same y axis

19 views (last 30 days)
Hello there,
I have two sets of parameter, x1 and x2 and they both vary with depth. Since the scale span of x1 is different to that of x2, what I want to do is to put the axis of x2 above, as the secondary plot (see fig below). Anyone can help me to fix this?
x1 = 0:0.1:5;
y1 = 0:1:50;
y2 = 0:1:90;
x2 = y2.^0.9;
figure;
subplot(1,2,1)
plot(x1,y1);
ylabel('Depth (m)');
xlabel('Length');
subplot(1,2,2);
plot(x2,y2,'r');
ylabel('Depth (m)');
xlabel('Power');
Please find attached the data, or please access the code above to generate the data.
Thanks
  2 Comments
Adi Purwandana
Adi Purwandana on 20 May 2024
Have you tried it? It's for yy axis not the x axis. I read already that link before and I can't manage it. Let me know if you try and have the solution.
Rik
Rik on 20 May 2024
A recent question also asked about two x axes in one plot. Where did you search?

Sign in to comment.

Accepted Answer

Piyush Kumar
Piyush Kumar on 20 May 2024
Hi Adi,
It seems like you want x2 to be plotted against y2 but have its x-axis aligned at the top nd y-axis synchronized with the y1.
x1 = 0:0.1:5;
y1 = 0:1:50;
y2 = 0:1:90;
x2 = y2.^0.9;
t = tiledlayout(1,1);
% Create the first axes
ax1 = axes(t);
plot(ax1, x1, y1, '-r');
ax1.XColor = 'r';
ax1.YColor = 'r';
% Create the second axes
ax2 = axes(t);
plot(ax2, x2, y2, '-k', 'Parent', ax2);
ax2.XAxisLocation = 'top';
ax2.YAxisLocation = 'right';
ax2.Color = 'none';
% Link the y-axes of ax1 and ax2
linkaxes([ax1, ax2], 'y');
ax2.YTick = [];
% ax2.YColor = 'none';
ax1.Box = 'off';
ax2.Box = 'off';
I have tried it almost the same way as it is mentioned in the "Display Data with Multiple x-Axes and y-Axes" section of the link. Also, I have used linkaxes function to synchronize the two y-axis.
  1 Comment
Adi Purwandana
Adi Purwandana on 20 May 2024
Edited: Adi Purwandana on 20 May 2024
Super! Thank you Piyush, I really appreciate your help.

Sign in to comment.

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!