The following example generates a figure containing two subplots. Each subplot contains two data sets plotted on separate axes using PLOTYY. The first subplot does not contain a legend and everything plots correctly. In the second subplot, one axes resizes once the legend is inserted.
x = 0:0.01:200;y1 = 200*exp(-0.05*x).*sin(x);y2 = (5*sqrt(x));figure(1);ylim1 = [-200 200];ylim2 = [0 80];ylim3 = [-250 250];xlim = [0 200];%subplot(1,2,1)
subplot(1,2,1)[ax1,h1,h2] = plotyy(x,y1,x,y2,'line');set(h1,'Color','g');set(h2,'Color','r');set(ax1(1),'YColor','k','Ylim',ylim1,'YTick',-200:100:200,'XLim',xlim,'xtick',0:25:200);set(ax1(2),'YColor','k','Ylim',ylim2,'YTick',0:20:80,'XLim',xlim,'xtick',0:25:200);set(get(ax1(1),'Ylabel'),'String','Left Ylabel','FontSize',8,'Color','g');set(get(ax1(2),'Ylabel'),'String','Right Ylabel','FontSize',8,'Color','r');xlabel('Time (ms)','FontSize',8,'Color','k');%subplot(1,2,2)
subplot(1,2,2)[ax2,h12,h22] = plotyy(x,y1,x,y2,'line');set(h12,'Color','m');set(h22,'Color','c');set(ax2(1),'YColor','k','Ylim',ylim3,'YTick',-200:100:200,'XLim',xlim,'XTick',0:25:200);set(ax2(2),'YColor','k','Ylim',ylim2,'YTick',0:20:80,'XLim',xlim,'XTick',0:25:200);set(get(ax2(1),'Ylabel'),'String','Left Ylabel','FontSize',8,'Color','m');set(get(ax2(2),'Ylabel'),'String','Right Ylabel','FontSize',8,'Color','c');xlabel('Time (ms)', 'FontSize', 8);L=legend('Left');
To verify this:
1. Insert a breakpoint just before creating the legend.
2. Compare the Position properties of the four axes: ax1(1), ax1(2), ax2(1), and ax2(2) before the legend is created using the GET command as follows:
get(ax1(1),'Position')
3. Step through the code to create the legend
4. Compare the Position properties of the four axes again.
You can see from the figure that one axes in subplot(1,2,2) appears to have shrunk, causing the XTicks to misalign.
Best Answer