MATLAB: Fix the limits of Yaxis secondary axis

bar and linelimits secondary yaxisplotset the limits

Hi,
I have the following code which I am duplicating for 6 different data sets. I want to limit the Y secondary axis from -25 -20 -15 -10 -5 0 5 10 15 20 25. I have posted the code below but it does not work even though I have given the limits. Can somebody help me to figure this out.?
Thanks in advance.
YearlyAnnualZ2=[1389.0;1663.1;1639.6;1776.6;1811.5;1346.8;1615.9;1578.6;1612.7;1497.3;1786.1;1315.7;1519.4;1864.0;1590.8];
AnnualZ2=[1292.1;1553.9;1718.8;1815.4;1856.5;1339;1840.9;1637.0;1509.9;1420.9;1965.3;1163.6;1319.3;1866.7;1706.1];
error=[-6.9768;-6.5677;4.8270;2.1831;2.4827;-0.5803;13.9195;3.6932;-6.3774;-5.1068;10.0316;-11.5617;-13.1733;0.1414;7.2471];
ZonalMean=[1600.5];
y=[YearlyAnnualZ2 AnnualZ2];
h=bar('v6',y,1,'group');
set(h(1),'facecolor','blue')
set(h(2),'facecolor','green')
months =['1998';'1999';'2000';'2001';'2002';'2003';'2004';'2005';'2006';'2007';'2008';'2009';'2010';'2011';'2012'];
set(gca,'XTick',1:1:15)
set(gca,'XTickLabel',months,'fontsize',14)
set(gca,'TickLength',[0.0005 0.0005])
xlim([0 16]);
ylim([600 2800]);
xL = get(gca,'XLim');
line(xL,[ZonalMean ZonalMean],'Color','b','LineWidth',2,'LineStyle','-');
line(xL,[mean(AnnualZ2) mean(AnnualZ2)],'Color','g','LineWidth',2,'LineStyle','-');
xlabel(''),ylabel('Precipitation (mm)')
% Plot with a secondary axis in the same above developed bar graph
mon=1:1:15;
h1 = gca;
h2 = axes('Position',get(h1,'Position'));
L1=plot(mon,error,'-ro','LineWidth',2.0,'MarkerSize',8);
hold on
set(h2,'YAxisLocation','right','Color','none','XTickLabel',[],'fontsize',12,'YColor', 'r')
set(gca,'XTick',1:1:15)
set(gca,'YTickLabel',[-25 -20 -15 -10 -5 0 5 10 15 20 25],'fontsize',12)
set(gca,'TickLength',[0.0005 0.0005])
set(h2,'XLim',get(h1,'XLim'),'Layer','top')
set(gca,'box','off'); % here gca means get current axis
ylabel('Error (%)','FontSize',12)
k1 = legend(h,'TRMM Avg.Annual','Station Annual',1);
set(k1,'Orientation','vertical','Visible','on',...
'FontSize',12,'Box','off');

Best Answer

Try setting the y-axis limits of the axes before changing the labels. Just change
set(gca,'YTickLabel',[-25 -20 -15 -10 -5 0 5 10 15 20 25],'fontsize',12)
to
set(gca,'YLim',[-25 25],'YTickLabel',[-25 -20 -15 -10 -5 0 5 10 15 20 25],'fontsize',12)
so that the tick labels fit within the limits for that axis.