Struggling with legend on grouped bar charts (Matlab)
Mostra commenti meno recenti
Hi,
I am struggling to set up properly the legend on a grouped bar chart that I have generated. My grouped bar chart looks like this:

As it can be seen on the legend, the second entry (2015 Data) appears on dark blue which is the same colour as the first entry (2014 Data). However, it should appear on light blue colour instead. This is the code that I am using:
bar(1:numel(Groups),[element1_2014 element2_2014 element3_2014],1,'FaceColor',[0.2,0.2,0.5]);
tickStep=1;
set(gca,'xtick',1:tickStep:numel(Groups))
set(gca,'xticklabel',Groups(1:tickStep:numel(Groups)))
set(gca,'ytick',-0.3:0.1:0.3)
axis([-Inf Inf -0.3 0.3])
hold on
bar(1:numel(Groups),[element1_2014 element2_2015 element3_2015],0.5,'FaceColor',[0,0.7,0.7],'EdgeColor',[0,0.7,0.7]);
hold off
legend('2014 Data','2015 Data')
Does anybody know how can I fix the second legend entry (2015 Data) so that it appears in light blue?. Thank you!.
4 Commenti
Star Strider
il 14 Giu 2015
I don’t have your data so I can’t run your code, but with this adaptation of it, the legend displays correctly (in R2015a):
C = mat2cell(rand(1,6), 1, ones(1, 6)); % Create Data
[element1_2014, element2_2014, element3_2014, element1_2015, element2_2015, element3_2015] = C{:};
bar(1:3, [element1_2014 element2_2014 element3_2014],1,'FaceColor',[0.2,0.2,0.5]);
hold on
bar(1:3,[element1_2014 element2_2015 element3_2015],0.5,'FaceColor',[0,0.7,0.7],'EdgeColor',[0,0.7,0.7]);
hold off
legend('2014 Data','2015 Data')
NC
il 15 Giu 2015
Star Strider
il 15 Giu 2015
We do not have your data, so we cannot run your code. There may be something about your data that would cause the result you posted in your original Question.
NC
il 15 Giu 2015
Risposta accettata
Più risposte (1)
Joseph Cheng
il 15 Giu 2015
Well if we start by reading the documentation on legend() we see that we can obtain the handles of a legend and modify the parameters. by adding the following at the end. you change the facecolor of the rectangle shown in the legend box.
legend('2014 Data','2015 Data')
[LEGH,OBJH,OUTH,OUTM] = legend;
set(get(OBJH(4),'children'),'faceColor',[0,0.7,0.7])
Now playing around with the data and the documentation we know that the OBJH is the items in side the legend. and the order indexed is texts from top to bottom, then marker top to bottom. If it is a line plot it'll be the same (texts, line, marker).
Since you specifically are labling and
1 Commento
Categorie
Scopri di più su Legend in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
