Plotting 2 x-axes against 1 y-axis
18 views (last 30 days)
Show older comments
Hi,
I am looking to add a second x-axis (measuring time) at the top of the plot seen below. The time corresponds to the number of cycles (approx 275 cycles per day) and should be reaching a maximum value of 20 years (tick mark every 1 or 2 year(s)). I would like to set up the second axis (measuring time) as an array such as: " x2 = 0:1:20; ".I have tried using some of the answers provided to other questions however it is not working for me.
My code for the plot is as follows:
figure(3)
plot(dN, ava)
title('Monte Carlo Simulation 200000','FontSize',14)
xlabel('Number of Cycles')
ylabel('Crack size (mm)')
ylim([0 20])
xlim([0 (total_cycles+50000)])
Thanks!
0 Comments
Accepted Answer
Dave B
on 26 Feb 2024
Edited: Dave B
on 26 Feb 2024
You can do something like this by creating a second axes, and in these cases it can be handy to use a tiledlayout to keep the two axes objects aligned. Make sure that you either do you plotting before creating the second axes (if the units of dN match the bottom axis units), or specify ax1/ax2 as the first argument for plot...
ax1=nexttile;
total_cycles = 2e6;
plot(linspace(0, total_cycles, 100), randn(1,100)+10)
xlim([0 total_cycles + 50000])
xlabel('Number of Cycles')
ylabel('Crack size (mm)')
ax2=axes(ax1.Parent, ...
'XAxisLocation','top','Color','none','XLim',[0 20],'XTick',0:2:20);
linkaxes([ax1 ax2],'y') % This is desirable if you want to plot into either axes
ylim([0 20])
title('Monte Carlo Simulation 200000','FontSize',14)
4 Comments
Dave B
on 26 Feb 2024
Ah yes, good point, We can turn off the box to hide the extra tick marks at the top. This will also remove the axis at the right, hopefully that is okay! And we should probably also hide the duplicated y axis, even though you can't really see it.
With respect to your line, you'll want to make sure that you know which of the two axes you're targeting now that there are two. In truth it doesn't matter much because [0 2e6] would work for both, but I think the 'hold on' is out of order.
ax1=nexttile;
total_cycles = 2e6;
plot(linspace(0, total_cycles, 100), randn(1,100)+10)
xlim([0 total_cycles + 50000])
xlabel('Number of Cycles')
ylabel('Crack size (mm)')
box off
ax2=axes(ax1.Parent, ...
'XAxisLocation','top','Color','none','XLim',[0 20],'XTick',0:2:20);
linkaxes([ax1 ax2],'y') % This is desirable if you want to plot into either axes
ylim([0 20])
title('Monte Carlo Simulation 200000','FontSize',14)
ax2.YColor='none';
xlabel('Time (years)')
hold(ax1,'on')
lineyy = [5 5];
linexx = [0 2e6];
plot(ax1,linexx,lineyy,'k-','Color','r','LineWidth',0.5)
% note you could also do use yline for simplicity:
% yline(ax1, 5, 'r')
See Also
Categories
Find more on Geographic Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!