MATLAB: Legend for plotyy causes axes problem

axislegendplotyy

Hello!
Can anyone help me?
The legend in my plot generated by plotyy causes a displacement of one y-axis.
Does anyone knows a solution? Thanks
x = 1:100;
y1= randn(1,length(x));
y2= randn(1,length(x));
y3= randn(1,length(x));
y4= randn(1,length(x));
% plot1
[hA,h1,h2] = plotyy(x,y1,x,y2);
hold on
% plot2
[hB,h3,h4] = plotyy(x,y3,x,y4);
hold off
legend([h1,h2,h3,h4],'a','b','c','d','location','northoutside','orientation','horizontal')
refresh

Best Answer

There are multiple axes created by plotyy and hold operates on only one at a time (and, disappointingly, won't accept a vector of multiple handles). Then, on top of that, when you use plotyy a second time you end up creating yet a third axis...
After executing your plotting calls--
>> [hA; hB] % look at axes handles...
ans =
173.0382 175.0382
173.0382 180.0382
>>
Note the LH axes was plotted into with the second call but a second RH axis was created. So, now you've got three to try to synchronize if you do that. So, "don't DO that!!!" :)
Instead,
>> [hA,h1,h2] = plotyy(x,y1,x,y2); % first call to create the two axes
>> set(hA,'nextplot','add') % "hold on" for multiple axes
>> h3 = plot(hA(1),x,y3); % add to the LH axis
>> h4 = plot(hA(2),x,y4); % and to the RH one as well
>> legend([h1,h2,h3,h4],'a','b','c','d','location','northoutside','orientation','horizontal')
>>
Now axes will be in synch and both reduced to place the legend as desired.