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

353 次查看(过去 30 天)
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 个评论
Aleksander Marek
Aleksander Marek 2016-9-27
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 2016-9-27
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.

请先登录,再进行评论。

回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by