I was able to figure out the question myself with a little less than desired solution. By creating two new variables, topC and bottomC, I was able to add in an if statement that assigned the value of C or a value of 0 to the new variables at the current index based on the criteria I was previously using for the bar graph commands. Now I just plot topC and bottomC instead and it works fine.
change bar color based on value
조회 수: 38 (최근 30일)
이전 댓글 표시
Hi,
I am trying to debug a code that will take two identical functions, A = randi([-100,100]) and B = randi([-100,100]), which each have their own unique values and input them into a third function, C = A - B. The code runs on a loop so it determines a value for A, B and C, and then plots the value in real time on three separate plots before moving on to the next number. I have a code that is supposed to plot the value of C on bar graph with the color green or red based on the value of C (green if C >= 0, red if C < 0). However, the code that I have ends up taking whatever the first color that was plotted and plots all bars in that color. The code that I currently have is as follows:
for i = 1:100;
A(i)=randi([-100,100]);
B(i)=randi([-100,100]);
C(i)=A(i)-B(i);
subplot(2,2,1)
plot(A,'b')
hold on
subplot(2,2,3)
plot(B,'k')
hold on
subplot(2,2,[2,4])
bar(C(C(:,1)>=0,:),'g');
hold on
bar(C(C(:,1)<0,:),'r');
hold off
drawnow
end
Any help to figure out where I'm going wrong in my code is greatly appreciated.
댓글 수: 0
채택된 답변
추가 답변 (2개)
David Goodmanson
2017년 12월 13일
Hi Morgan,
Unless you are trying to make a movie*, it's faster and more Matlablike to create A and B all at at once:
N = 100;
span = [-100 100];
A = randi(span,1,N);
B = randi(span,1,N);
C = A-B;
figure(1)
subplot(2,2,1)
plot(A,'b')
subplot(2,2,3)
plot(B,'k')
subplot(2,2,[2,4])
bar(C(C>=0),'g')
hold on
bar(C(C<0),'r')
hold off
I don't know exactly why the colors don't work for the for loop, but this way they do work all right.
*(there are more efficient ways to do that then replotting the entire array each time).
댓글 수: 2
Benjamin Kraus
2017년 12월 13일
You should check out the latest version of MATLAB. Starting in MATLAB R2017b you can specify a color for each bar in a bar series independently.
In your case, I think this will work:
b = bar(C, 'FaceColor', 'g');
b.FaceColor = 'flat';
b.CData(C<0,:) = repmat([1 0 0],sum(C<0),1);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Bar Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!