How to set YTickLabel in double y-axis plot?
6 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
dpb
on 22 Mar 2016
Edited: dpb
on 23 Mar 2016
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 Comments
dpb
on 22 Mar 2016
>> help transpose
.' Transpose.
X.' is the non-conjugate transpose.
I commented specifically on the need and what happens without it...
More Answers (1)
See Also
Categories
Find more on Axis Labels in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!