![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/175145/image.png)
Change Bar Graph Legend Color?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Kevin
am 23 Jun. 2014
Bearbeitet: Star Strider
am 24 Jun. 2014
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 Kommentare
Akzeptierte Antwort
Star Strider
am 24 Jun. 2014
Bearbeitet: Star Strider
am 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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/175145/image.png)
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 Kommentare
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!