user2011560
user2011560

Reputation: 75

Matlab, legends in a barplot

I'm having a for loop which creates a barchart with 4 bars on the basis on 2 vectors. two bars are red and two are green. Red and green means two different things. I would like to show that in a legend, but how am I going to do it. I've tried several things but nothings seems to do what i want. My latest output gave a legend like this:`

'red color' Wrong answer
'red color' Wrong answer
'green color' right answer'
'green color' right answer

as you can see the output gave me 4 legends but I just want 2. How can fix this:

R = [-1 -1 1 1];
T = [2.0741 2.1521 2.9529 2];
figure;  
% Barchart
for i=1:length(T)
   h = bar(i, T(i));
     if i == 1 hold on, end
     if R(i) == -1
       col = 'r';
       legendInfo{i} = ['Wrong answer '];
     else
       col = 'g';
       legendInfo{i} = ['Right answer '];
     end

     set(h, 'FaceColor', col)

end

set(gca,'xTick',1:length(R),'xTickLabel',1:length(R))
xlabel('question number.');
ylabel('time per question')
legend(legendInfo)

Upvotes: 1

Views: 96

Answers (1)

Daniel
Daniel

Reputation: 36710

You can pass handles to legend to specify which entries you want to have:

R = [-1 -1 1 1];
T = [2.0741 2.1521 2.9529 2];
figure;  
% Barchart
for i=1:length(T)
   h(i) = bar(i, T(i));
     if i == 1 hold on, end
     if R(i) == -1
       col = 'r';
       legendInfo{i} = ['Wrong answer '];
     else
       col = 'g';
       legendInfo{i} = ['Right answer '];
     end

     set(h(i), 'FaceColor', col)

end
set(gca,'xTick',1:length(R),'xTickLabel',1:length(R))
xlabel('question number.');
ylabel('time per question')

[~,legendsIWant]=unique(R)
legend(h(legendsIWant),legendInfo(legendsIWant));

Upvotes: 2

Related Questions