Problem with XTick: location of XTick doesn't match data.

2 Ansichten (letzte 30 Tage)
Xiaohan Du
Xiaohan Du am 23 Mai 2018
Kommentiert: Xiaohan Du am 25 Mai 2018
Hi all,
I have the following script to plot 2 curves with 2 x-axis on top and bottom:
clear; clc; clf;
errxOri = [4 6 8 10 13 14 18 20 24 34 39];
errOriMax = [0.5279 0.37978 0.30287 0.19383 0.13164 0.11567 0.093856 ...
0.080826 0.05997 0.046702 0.033662];
errxPro = [4 7 8 10 12 14 22 26 30 33 38];
errProMax = [0.5279 0.38693 0.21168 0.16633 0.1322 0.1168 0.10034...
0.068223 0.060327 0.047501 0.032004];
figure(1)
ha1 = semilogy(errxOri, errOriMax, 'b-o', 'MarkerSize', 10, 'lineWidth', 3);
hold on
ha2 = semilogy(errxPro, errProMax, 'r-+', 'MarkerSize', 10, 'lineWidth', 3);
ax1 = gca;
ax1.XColor = 'b';
ax1.XTick = errxOri;
set(gca,'fontsize',20)
ax2 = axes(...
'Position', ax1.Position,...
'XAxisLocation', 'top',...
'Color', 'none',...
'YTick', [],...
'XLim', [0 39],...
'XTick', errxPro);
ax2.XColor = 'r';
ax2.XTick = errxPro;
set(gca,'fontsize',20)
grid on
But running it gives the following plot:
As you can see it does most of the job, just the xticks on top doesn't match the data (red cross), you can see the red cross is slightly offset from the vertical grid line. Why does this happen? How to fix it?
Many thanks!

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 23 Mai 2018
You do not specify the xlim for the first axes and the two axes are not linked.
  3 Kommentare
Walter Roberson
Walter Roberson am 23 Mai 2018
"Why does xlim of the first curve link with the xtick of the second curve?"
They are not linked.
In the first axes, which displays both semilogx plots, you set XTick as errxOri which is values in the range 4 to 39. The X of your first plot, ha1, is errxOri which goes up to 39, and you never set XLim for that axes, so XLim will be automatically determined as going up to at least 39, but possibly further. The next "nice" round number for the range of values used is 40, and the "nice" round number below the low data limit of 4 is 0, so the XLim is set to [0 40].
In the seconds axes, which has no content but sets tick labels for the top, you set XTick as errxPro, which goes up to 38 (not 39). You set XLim specifically as [0 39].
So now you have a slight difference in scaling between the two systems. One is [0 40] because the limits were constructed automatically by data, and the other is [0 39] because you hard-coded that.
You should consider making the XLim of the second axes equal to the automatically generated XLim of the first axes.
Xiaohan Du
Xiaohan Du am 25 Mai 2018
Thanks Walter, very clear explanation! Problem has been solved now.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Formatting and Annotation finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by