How to set YTickLabel in double y-axis plot?

조회 수: 7 (최근 30일)
Albert Bing
Albert Bing 2016년 3월 22일
편집: dpb 2016년 3월 23일
The simplified code is as following:
x=[2,3,4,5,6,7];
y1=[ 1, 1, 1.2, 1.2, 1, 1];
y2=[ 0, 0.01, 0.02, 0.02, 0, 0.01];
fig1 = figure;
[ax,h1,h2] = plotyy(x,y1, x,y2, 'plot');
set(get(ax(1),'YLabel'),'String','y1','fontsize',14)
set(get(ax(2),'YLabel'),'String','y2','fontsize',14)
legend('y1','y2');
xlabel('x')
ylim(ax(1), [0.7, 1.3])
ylim(ax(2), [0, 0.03])
print(fig1, '-dpng', 'test1')
The figure plot is like
I wanted to set the digits of YTick, so I tried something like
set(get(ax(1),'YTick'), [1.00, 1.05, 1.10, 1.15, 1.20]);
set(get(ax(1),'YTickLabel'), [1.00, 1.05, 1.10, 1.15, 1.20]);
or
set(get(ax(1),'YTick'), {'1.00', '1.05', '1.10', '1.15', '1.20']);
set(get(ax(1),'YTickLabel'), {'1.00', '1.05', '1.10', '1.15', '1.20']);
or
set(get(ax(1),'YTick'), str2mat('1.00', '1.05', '1.10', '1.15', '1.20']);
set(get(ax(1),'YTickLabel'), str2mat('1.00', '1.05', '1.10', '1.15', '1.20']);
All went wrong.
So my question is, how to set the digits of y axis label?
And why the left YTick is from 1.0 to 1.2 but leaves all other ticks?
And more generally, how to handle this `gca` properties?

채택된 답변

dpb
dpb 2016년 3월 22일
편집: dpb 2016년 3월 23일
Isn't it annoying that plot isn't intelligent-enough to use a consistent numeric format for tick labels??? I've complained about this for almost 30 years now... :(
Anyway, it's relatively easy to fix...
Long-winded way; easier to see what did...
yt=get(hAx(1),'ytick'); % retrieve the tick marks from desired axes
set(hAx(1),'yticklabel',num2str(yt.','%.2f')) % set with a desired format same values
You can, of course, dispense with the temporary -- easiest to write w/o getting fouled up with parentheses nesting if start from inside out...
set(hAx(1),'yticklabel',num2str(get(hAx(1),'ytick').','%.2f'))
NB: the transpose; it's important as the tick values are returned as a row vector and num2str needs a column vector or the values will all be returned as a single long string, not an array of strings.
  댓글 수: 3
dpb
dpb 2016년 3월 22일
>> help transpose
.' Transpose.
X.' is the non-conjugate transpose.
I commented specifically on the need and what happens without it...
Albert Bing
Albert Bing 2016년 3월 22일
Ah, transpose, thank you!
So that better be
num2str(yt.', '%.2f')

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mike Garrity
Mike Garrity 2016년 3월 22일
Or in R2016a:
ax(1).YAxis.TickLabelFormat = '%.2f';

카테고리

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