user1936752
user1936752

Reputation: 858

Plot a legend for both a barplot and a line

If I have a barplot and then a line on the same graph, how do I write a legend for both? I have

hold on
h1 = bar([x;y], 0.5);
h2 = plot(a, b);
l = cell(2,1);
l{1,1}='Label for x';
l{2,1}='Label for y';
hl=legend(h1, l);
set(hl,'FontSize',10,'Location','Northeast', 'Orientation', 'horizontal');

This generates the legend for the barplot but how do I add the legend entry for the line plot?

Upvotes: 0

Views: 56

Answers (2)

Suever
Suever

Reputation: 65430

You've only passed the bar plot handle to the legend function so that's all it's going to create. What you can do, however, is pass an array of handles (and labels) to legend and legend entries for all elements of the handles array will be shown.

h1 = bar([x;y], 0.5);
h2 = plot(a, b);
labels = {'Label for x', 'Label for y'};
L = legend([h1, h2], labels, ...
            'FontSize', 10, ...
            'Location', 'Northeast', ...
            'Orientation', 'horizontal');

Upvotes: 2

blubbafett
blubbafett

Reputation: 168

One way to do it:

legend({'label for x','label for y'},'FontSize',10,'Location','Northeast','Orientation','vertical');

If you want to keep your cell object with the legend entries, you can use

l = cell(2,1);
l{1,1}='Label for x';
l{2,1}='Label for y';
legend(l,'FontSize',10,'Location','Northeast','Orientation', 'vertical');

Upvotes: 1

Related Questions