Drawing different coloured bar plots according to different conditions

조회 수: 2 (최근 30일)
Go Sugar
Go Sugar 2022년 9월 25일
댓글: Go Sugar 2022년 9월 28일
Hello =),
I have an excel file that looks something like this:
Participant A_1 A_2 A_3 A_4 B_1 B_2 B_3 B_4 C_1 C_2 C_3 C_4
1 1 2 1 2 35 40 23 36 0 0 1 1
2 2 1 1 1 80 54 88 25 1 1 0 0
I have 2 subjects (participants). I want to draw different bar plots for each A, B and values separately for each participant. My problem is that I need to provide different colours according to each value of A and C.
When A=1 and C=1, bar plot colour=red,
When A=1 and C=0, bar plot colour=yellow,
When A=2 and C=1, bar plot colour=green,
When A=2 and C=0, bar plot colour=black,
As a result I can have bar plots of A and C separately for each participant with coloured according to variables A and C.
I also want to bar plot variable B with the same colours provided before (according to the same colour numbers 1,2,3 and 4).
So at the end I want to have bar plots of A, B and C for each participant.
Thank you so much. :)

채택된 답변

dpb
dpb 2022년 9월 25일
Well, let's see if I parsed this correctly...
data =[
1 1 2 1 2 35 40 23 36 0 0 1 1
2 2 1 1 1 80 54 88 25 1 1 0 0];
P=data(:,1); A=data(:,2:5), B=data(:,[2:5]+4), C=data(:,[2:5]+8);
A = 2×4
1 2 1 2 2 1 1 1
B = 2×4
35 40 23 36 80 54 88 25
%C={'y','r','k','g'}; % wished-for colors in order
NC=[1 1 0;1 0 0;0 0 0;0 1 0]; % RGB triplets to match
fnC=@(a,c) (2*(a-1)+c+1); % lookup function -- color index as FN(A,C)
hB=bar(B(1,:),'FaceColor','flat'); % draw a sample bar for one B
for i=1:size(B,2) % set bar colors to lookup value
hB.CData(i,:)=NC(fnC(A(1,i),C(1,i)),:); % have to set the CData() property w/ RGB triplet
end
ylabel('B Participant 1'); xlabel('Observation')
For the others, mimic the above -- can be written with looping constructs over Participant (row) and also with indexing into larger data array to avoid the multiple variables used here to improve legibility.
You can set any choice of RGB triplets to not be quite so garish as suits...
  댓글 수: 3
dpb
dpb 2022년 9월 28일
"...how did you write the lookup function?"
Simply by inspection and ordering the color vector in the specific order to match.
The two variables A,C each vary by one; shifted A to also be 0-1, then the factor of two is the second bit in a 2-bit encoding 0-3; the "+1" produces a valid one-based array index. I deliberately left written as is so can see the two factors rather than simplifying the expression.
Go Sugar
Go Sugar 2022년 9월 28일
It now makes sense, thank you so much for all the help.. =) Have a great day!..

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Bar Plots에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by