MATLAB: How to get consistent subplot widths with legend outside

legend locationsubplot

I want to put my legends outside the plot so they never cover any data, but also want the subplots to have the same width since they'll all have the same X data. If the legends have variable width, the auto-positioning makes the sub plots different widths. Is there anyway to get around this?
subplot_ex.jpg

Best Answer

You can assign a handle to the legends and set all their xpositions to be the same. Do the same for the subplots.
ex:
%some_x_position = whatever you want
%some_length = whatever you want
s1 = subplot(3,1,1)
plot(x1,y1)
l1 = legend
l1.Position(1) = some_x_position % position is an array of [x y l h ]
s1.Position(3) = some_length
s2 = subplot(3,1,2)
plot(x2,y2)
l2=legend
s2.Position(3) = s1.Position(3)
l2.Position(1) = l1.Position(1)
s3 = subplot(3,1,3)
plot(x3,y3)
l3=legend
s3.Position(3) = s1.Position(3)
l3.Position(1) = l1.Position(1)
note: you can call out the handles to see if their position is 'normalized' (w.r.t. figure) or 'pixels'. and set your x position / lengths accordingly.
Related Question