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

조회 수: 3 (최근 30일)
Xiaohan Du
Xiaohan Du 2018년 5월 23일
댓글: Xiaohan Du 2018년 5월 25일
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