add legend matlab plot

╄→尐↘猪︶ㄣ 提交于 2019-12-24 13:25:36

问题


I have a matlab function myfunction(var1,var2) which gives me a plot with a legend. I would like to generate more plots with this function in one graph. This works so far i.e. for 2 plots in one graph with:

myfunction(a,b)
hold on
myfunction(c,d)
hold off

The problem here is that the legend which is generated for each plot with:

legend(sprintf('%s%s',var1,' on ',var2))
legend('boxoff')

is only appearing for the last instance of myfunction (in this case with myfunction(c,d), there would be only one line of legend where it says 'c on d', but I would like to have two lines with 'a on b' and 'c on d')

So how can I add something to the legend without overwriting it?


回答1:


Another possibility is to use the dynamic legend (not so-well documented) feature of MATLAB. In your case, instead of passing the legend captions to the legend function, you'll need to use them as input arguments to the plot function:

plot(x, y, 'DisplayName', 'caption');

and then add the legend using the following syntax:

lh = legend('-DynamicLegend');
set(lh, 'Box', 'off');

However, I wouldn't suggest this approach if you have a large number of graphs to be rendered on the same plot as fast as possible, e.g. in a loop. In these cases the dynamic legend might cause a significant performance hit.




回答2:


If you're going to be doing this a lot it might be best to export the legend labels as an output argument of your function, then concatenate them and call legend outside the function.

If it's just a hack then inside your function you could look at the axis handle and pull the legend entries out. There's a similar question here that does that.



来源:https://stackoverflow.com/questions/30028318/add-legend-matlab-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!