Change Bar Graph Legend Color?

조회 수: 2 (최근 30일)
Kevin
Kevin 2014년 6월 23일
편집: Star Strider 2014년 6월 24일
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