Change Bar Graph Legend Color?

1 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2014-6-24
编辑:Star Strider 2014-6-24
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.)

更多回答(1 个)

the cyclist
the cyclist 2014-6-23
Try
legend([hbc{:}],'old','new');

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by