Change Bar Graph Legend Color?
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Star Strider
il 24 Giu 2014
Modificato: Star Strider
il 24 Giu 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 Commenti
Più risposte (1)
Vedere anche
Categorie
Scopri di più su Legend in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!