Creating a Legend for Two Bar Plots (Plotted Together on Same Figure)

14 views (last 30 days)
Hi, I am having trouble getting a legend that incorporates both bar graphs (one white & one black) that are plotted together on the same figure using 'hold on'. Each bar also has an error bar. An example of my code is:
figure;
errorbar(x, meanValue, lowerError, upperError, 'k', 'LineStyle', 'none');
hold on;
bar(x, meanValue, 'w');
errorbar(x, -meanValue2, -upperError2, -lowerError, 'k', 'LineStyle', 'none');
bar(x, -meanValue2, 'k');
legend('Label1','Label2');
When I do this, the legend has no color for Label1 (black), but has a color for Label2 (white). How can I get the black color to show up in the legend for Label1. Any help would be greatly appreciated. Thank you.
  1 Comment
Danny
Danny on 23 Jun 2011
I also need help inserting a legend for a boxplot with two colors (red & blue). My code for this is:
boxplot(data, 'notch', 'on', 'symbol', '*','colors','rb');
legend('Label1','Label2');
But I get no legend and it says "Warning: Plot empty" in the command window. Any help on this matter would be great as well. Thank you.

Sign in to comment.

Accepted Answer

Patrick Kalita
Patrick Kalita on 23 Jun 2011
With that syntax, legend is assuming you want to include in the legend the first two things plotted -- namely the first set of error bars and the first bar graph. Instead, what you should do is save the handles to the bar graphs, and tell legend that those are what you want to include by passing the handles to it:
figure;
errorbar(1:10, 1:10, 0.1:0.1:1, 0.1:0.1:1, 'k', 'LineStyle', 'none');
hold on;
b1 = bar(1:10, 1:10, 'w');
errorbar(1:10, -(1:10), -( 0.1:0.1:1), -(0.1:0.1:1), 'k', 'LineStyle', 'none');
b2 = bar(1:10, -(1:10), 'k');
legend([b1 b2], 'Label1','Label2');
  1 Comment
Danny
Danny on 23 Jun 2011
Thank you so much for your help, sometimes I forget the simple solutions. Also I need some help inserting a legend for a boxplot. My code is:
boxplot(data, 'notch', 'on', 'symbol', '*','colors','rb');
so that every boxplot alternates between red and blue. A legend doesn't seem to work here. Thanks again for all your help.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!