Adding to a legend after each iteration

前端 未结 5 1624
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 15:13

I run

loglog(x,y);
legend(\'First script\');

from the first script. Then, hold on;. I run a similar second script. I see two g

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 16:02

    The easiest way to deal with this is to save the handle to the legend when you create it, then whey you are ready to update the plot with a new legend with another series included, delete the legend and make a new one:

    legendStrings = {'First script'};
    h_legend = legend(legendStrings{:});
    % ... computations, hold on and additional plot on axis
    delete(h_legend);
    legendStrings{end+1} = 'Second script';
    h_legend = legend(legendStrings{:});
    % rinse and repeat...
    

    Usually with graphics objects, such as a textbox, I would say just reuse the object via the handle (don't delete). However, if you update the legend instead of replacing it, you have to worry about more than just the strings. The MathWorks solution referenced by zroth actually seems to address this approach!

    As an alternatively to delete and create new, you can also toggle the legend on and off with legend('off'); legend('show'); as the answer in Eugenio's comment suggests.

提交回复
热议问题