Change Bar Graph Legend Color?
2 views (last 30 days)
Show older comments
Y = [-3,-2;2,1;1,-1;4,3;-1,4];
hb = bar(Y);
hbc = get(hb, 'Children');
set(hbc{1}, 'FaceColor', 'r');
set(hbc{2}, 'FaceColor', 'g');
legend('old','new');
The above code generates a bar graph with two sets of overlaying bars. I changed the default bar color for each set of bars, but the legend as it stands does not reflect these changes. How can I correct this?
Thanks.
0 Comments
Accepted Answer
Star Strider
on 24 Jun 2014
Edited: Star Strider
on 24 Jun 2014
I had to do some really deep handle-diving, but I finally figured out how to link them to the colors you choose for the bars and set them so they will change automatically.
The code:
Y = [-3,-2;2,1;1,-1;4,3;-1,4];
hb = bar(Y);
hbc = get(hb, 'Children');
set(hbc{1}, 'FaceColor', 'r');
set(hbc{2}, 'FaceColor', 'g');
hl = legend(hb,'old','new');
hbch1 = get(hbc{1}, 'FaceColor');
hbch2 = get(hbc{2}, 'FaceColor');
hc = findobj(hl, '-property', 'FaceColor');
set(hc(2), 'FaceColor', hbch2)
set(hc(1), 'FaceColor', hbch1)
The plot thickens:
If you want to save it though, you have to do it progrmatically. The ‘Save’ options in the figure window somehow cause the legend to revert. So use:
print(gcf, 'Change Bar Graph Legend Color', '-dpng')
to get it to save correctly. (Change its name and directory to your preference.)
0 Comments
More Answers (1)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!