Problem with XTick: location of XTick doesn't match data.
3 次查看(过去 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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/190773/image.png)
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!
0 个评论
采纳的回答
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
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Axis Labels 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!