Reputation: 77
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?
Upvotes: 1
Views: 1014
Reputation: 486
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.
Upvotes: 0
Reputation: 1635
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.
Upvotes: 0