7

I have a figure with 5 subplots. I declare subplot(2,3,X) which includes 6 subplots. The 6th subplot is empty. I am going to move legend to 6th empty position for all plots.

How is it possible?

BlueBit
  • 397
  • 6
  • 22

2 Answers2

4

if you just want to use standard-matlab, you need the handle of the subplot and then you need its position. Then you set the position of the legend to the position of the subplot. Referring to the docs:

Note You can set the legend location by passing the 4–element position vector to the legend function using the ‘Location' option. To define the position of an existing legend, use the set function to assign the 4–element position vector to the ‘Position' property. You cannot use the Location option with the set function

for example:

subplot(2,3,1), plot(1:10,2:11)
myLegend=legend('text1')
set(myLegend,'Units', 'pixels')
myOldLegendPos=get(myLegend,'Position')
hold on
h=subplot(2,3,6)
set(h,'Units', 'pixels')
myPosition=get(h,'Position')
set(myLegend,'Position',[myPosition(1) myPosition(2) myOldLegendPos(3) myOldLegendPos(4)])
Lucius II.
  • 1,832
  • 12
  • 19
  • 2
    This method did not work for me. If I copy/paste the code above in R2012b, the legend does not appear anywhere in the figure. The reason is that the second blank subplot "covers" the legend. One must add the line `set(h, 'Visible', 'off')` at the end to allow the legend to be visible. – Micah Smith Dec 23 '14 at 21:39
  • Or use `legend` with 'Location' set to a vector `[Position_Right_in_pct, Position_Top_in_pct, Horizontal_Stretch Vertical_Stretch]` See http://stackoverflow.com/a/35696869/3494126 – Ufos Feb 29 '16 at 10:14
3

Maybe try legendflex from the File Exchange, it looks like it can do what you want.

am304
  • 13,758
  • 2
  • 22
  • 40