简体   繁体   中英

add legend matlab plot

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 ie 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?

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.

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, eg in a loop. In these cases the dynamic legend might cause a significant performance hit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM