
Plot with two x axis and proper scaling/aligning
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
When making a plot with two x axis and two y axis how do you make sure that the ticks align/ are porperly scaled when the second x axis is a derivived value of the first x axis? So that for each tick on the lower x axis the correspoding derived value is displayed in the correct location on the upper axis and so the plots are the same in this case.
x1 = 0.06:0.01:0.5;
y1 = x1;
x2 = 0.7./(pi.*x1);
y2 = y1;
t = tiledlayout(1,1);
ax1 = axes(t);
plot(ax1,x1,y1,'-r')
ax1.XColor = 'r';
ax1.YColor = 'r';
grid on
ax2 = axes(t);
plot(ax2,x2,y2,'-k')
ax2.XAxisLocation = 'top';
ax2.YAxisLocation = 'right';
ax2.Color = 'none';
ax1.Box = 'off';
ax2.Box = 'off';
ax2.XDir = 'reverse';
grid on

0 Commenti
Risposte (1)
dpb
il 29 Apr 2022
Modificato: dpb
il 29 Apr 2022
The idea is to set the limits of the second axes to the values corresponding to those of the first so the two plots are identically over the same range, not letting the auto-ranging scale prettifier operate to make neat-looking tick labels as does by default.
Then, compute and set the second axes tick values to match those of the first -- simple to do in code, but in a case such as yours where the spacing is grossly nonlinear with increasing values of the first axis, the location of the second axes ticks gets to be too tight to have sufficient room to label them all.
Simpler, is to just write the tick label values that correspond to the ax1 values at those locations positionally, ignoring the actual tick values.
fnX = @(x) 0.7./(pi.*x); % should 0.7 be sqrt(2), maybe???
xlim(ax2,sort(fnX(xlim(ax1))))
to set the ranges to be consistent.
Then, to label the ticks on linear scale as those in ax1, compute the corresponding ax2 values and write them as ticklabels
xticklabels(ax2,compose('%0.2f',fliplr(fnX(xticks(ax1)))))
NB: the fliplr operation to account for the reversed axes direction; you're writing positional labels into the TickLabels property here, not setting XTick values.
The above produces

In general, it's not possible to have "pretty" numeric values on both axes when the relationship between the two is nonlinear and can be difficult even when linearly related.
It's interesting to actually write the corresponding ticks for the second axis; they are, of course, increasingly closer together as get to RH side of the plot and tick labels occlude each other -- and, they don't match up with the linear spacing of the other. The choice there is to write the labels on ax1 to match chosen of ax2.
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!