How to update the position of legend with 'Best' Location?

545 views (last 30 days)
Hi,
I have an output function which I use with fmincon to plot some of variables during optimization process. I use
legend(...,'Location', 'Best')
to define the legend, and in the first iteration it looks really okay. However, as the optimization goes, I update my graph with:
set(h, 'YData', new_data);
And sometimes the legend overlaps with the new plot (it doesn't reposition to adjust for new data). Is there any way I could reposition automatically my legend (I guess apart from deleting it and constructing again every iteration)?
Cheers, Aleksander
  3 Comments
Aleksander Marek
Aleksander Marek on 27 Sep 2016
Yesterday, I tried updating the legend's position with:
set(leg, 'Location', 'North')
set(leg, 'Location', 'Best')
drawnow
But the legend wouldn't move at all
dpb
dpb on 27 Sep 2016
That's actually what I expected; legend is just an m-file and set on the properties after the fact only changes that string recorded in the 'location' property; it doesn't trigger any callbacks or such.
You'd have to use a callback function when data are updated and that's more trouble than simply re-issuing the legend command each iteration.
While no doubt it's not as neat in appearance, if the redrawing is distracting during the simulation, you could place the legend outside the axes so it won't occlude the data and then try the 'best' location at the end for final viewing.

Sign in to comment.

Answers (1)

Massimo Zanetti
Massimo Zanetti on 27 Sep 2016
At every new plot reissue the command
legend(...,'Location', 'Best')
So that Matlab recomputes the right position to place it.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!