hello,
i want to plot my bar in two colors conditions.if Tr<0 the color is red else the color is green. Ihqve tryed this but it didn't works.
can you help me please
T=readtable('file.xlsx');
A=T{:,:};
Tr=A(:,1);
EPR=A(:,2);
for i=1:length(A)
h=bar(Tr,EPR)
hold on
if (Tr<0)
barcolor='r';
else
barcolor='g'
end
end

 채택된 답변

Andy
Andy 2020년 10월 22일

0 개 추천

figure();
hold on
for i=1:length(A)
if (Tr(i)<0)
h=bar(Tr(i),EPR(i),'r');
else
h=bar(Tr(i),EPR(i),'g');
end
end
hold off

댓글 수: 1

Rik
Rik 2020년 10월 22일
Just a note: it is bad design to use length for matrices. It is also probably not a good idea to create many bar objects, as that many graphics objects may cause performance issues.

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

추가 답변 (1개)

Rik
Rik 2020년 10월 22일
편집: Rik 2020년 10월 22일

0 개 추천

If you insist on separate bar objects you can use the first part, if not, you can use the second part
figure(2),clf(2)%ensure a clean figure for this example
A=rand(10,2)*5-2.5;%generate random data
Tr=A(:,1);
EPR=A(:,2);
subplot(1,2,1)
%for i=1:length(A)
for n=1:size(A,1)% or since R2020b: n=1:height(A)
width=0.05;
h=bar(Tr(n),EPR(n),width);
hold on
if (Tr(n)<0)
h.FaceColor='r';
else
h.FaceColor='g';
end
end
subplot(1,2,2)
L=Tr<0;
EPR_part=EPR;EPR_part(~L)=NaN;% this step is only require to make the bars the same width
bar(Tr,EPR_part,'r'),hold on
EPR_part=EPR;EPR_part( L)=NaN;
bar(Tr,EPR_part,'g'),hold off

댓글 수: 4

bekka mohamed
bekka mohamed 2020년 10월 22일
thank you for the answer,
the code did not work well. that shows a green plot bar. and for the width, i have 2560 values so width is not necessary. i just want to plot it with two colors with a specific condition
Rik
Rik 2020년 10월 22일
Did you run my code with the generated random data, or with only your own data? This code does what you describe when I run it on R2020b. What release are you using?
bekka mohamed
bekka mohamed 2020년 10월 22일
oh, my bad ! it was a probleme with my data . so the code works perfectly thank you for your effort
bekka mohamed
bekka mohamed 2020년 10월 22일
and am using R2018b

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

카테고리

도움말 센터File Exchange에서 Annotations에 대해 자세히 알아보기

태그

질문:

2020년 10월 22일

댓글:

Rik
2020년 10월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by