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

2 次查看(过去 30 天)
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!

采纳的回答

Walter Roberson
Walter Roberson 2018-5-23
You do not specify the xlim for the first axes and the two axes are not linked.
  3 个评论
Walter Roberson
Walter Roberson 2018-5-23
"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 2018-5-25
Thanks Walter, very clear explanation! Problem has been solved now.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Axis Labels 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by