Adding a secondary x axis on the top of a line plot

47 views (last 30 days)
In the line plot obtained after running the code appended below, xticks are to be added at the top such that their value is 50 times the xticks at the bottom of the plot. Moreover, an xlabel needs to be at the top also. Could someone help me with the code.
I had tried to implement some suggestions in previous posts on the topic, but somehow I get misaligned and overlapping axes. Thanks in advance.
x = 15:15:1800;
y1 = x./(1-x);
y2 = exp(-x./(1+x));
figure;
tiledlayout(1,1);
nexttile;
yyaxis left; plot(x/360,y1,'-bo'); hold on;
ylabel('PCC'); xlabel('time (days)');
yyaxis right; plot(x/360,y2,'-xr'); % hold on;
ylabel('DPCC (mm)'); % xlabel('time (days)');
axis square;
legend('PCC','DPCC','Location','East');

Accepted Answer

Prachi Kulkarni
Prachi Kulkarni on 24 Sep 2021
Hi,
Following is a modified version of your code which will give you the secondary X axis at the top of the plot with an xlabel as required.
x1 = 15:15:1800;
y1 = x1./(1-x1);
y2 = exp(-x1./(1+x1));
x2 = 50*x1;
t = tiledlayout(1,1);
ax1 = axes(t);
l1 = plot(ax1,x1,y1,'-bo');
ax1.Color = 'none';
xlabel('time (days)'); ylabel('PCC');
axis square
ax2 = axes(t);
l2 = plot(ax2,x2,y2,'-xr');
ax2.XAxisLocation = 'top';
ax2.YAxisLocation = 'right';
ax2.Color = 'none';
xlabel('Label for top X axis'); ylabel('DPCC (mm)');
axis square
legend([l1;l2],'PCC','DPCC','Location','East');
ax1.Box = 'off';
ax2.Box = 'off';
For more information, please refer to the following documentation on adding multiple X and Y axes to your plots.

More Answers (0)

Categories

Find more on Graphics in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!