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

barlegend

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.

Best Answer

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');