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
46 次查看(过去 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).
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 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!