Reputation: 75
I have a function plot_result()
which plots bars from the result on the basis of a test. I have two vectors:
R = [0 1 1 -1] containing logical true or false from the questions. and
T = [0 1 2 3] containing time spent on each questions.
0 - in R means a question not answered
a bar is green if the answer is 1 and red otherwise. But the legends show something else than expected.
in the above case R and T the legend show:
Green - "Right answer"
Green - "Right answer"
instead of
Green - "Right answer"
Red - "Wrong answer"
sometimes it also shows 3 legends instead of two - what am I doing wrong ?
R = [0 1 1 -1];
T = [0 1 2 3];
if sum(T) ~= 0
% Barchart
figure;
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
end
set(gca,'xTick',1:length(R),'xTickLabel',1:length(R))
xlabel('Answer No..');
ylabel('Time per. question')
title('Question vs. time')
set(gca,'YLim',[0 max(T)])
[~,legendsIWant]=unique(nonzeros(R));
legend(h(legendsIWant),legendInfo(legendsIWant),'Location', 'BestOutside' 'FontSize', 8);
Upvotes: 0
Views: 43
Reputation: 3587
The problem with the given input is [~,legendsIWant]=unique(nonzeros(R))
will give the indexes values corresponding to nonzeros(R) not R
a possible fix would be to get all unique values locations and then discard any corresponding to zero e.g. replace the line mentioned with
[uniqueValues,legendsIWant]=unique(R)
legendsIWant=legendsIWant(uniqueValues~=0)
Upvotes: 1