![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/172494/image.png)
Colouring Bars by 'Y' value
1 次查看(过去 30 天)
显示 更早的评论
Hello Community,
I am trying to plot a bar chart and to colour the bars according to a rule related to the values for the 'Y' axis. So, if the Y value is a minus figure, the bar should be coloured grey, and if positive, should be coloured black. I have tried the following (and several variations):
% Colouring bars
if y <0;
bar(y,'RGB::Grey');
elseif y >= 0;
bar(y,'RGB::Black');
end
but with no luck. Everything else about the plotting that I am doing works fine.
I'm sure this will be simple for the more experienced, so could anyone suggest a fix to help me please?
Thank you,
10B.
0 个评论
采纳的回答
Mike Garrity
2016-1-13
I would suggest the approach I described in this blog post. In this case, it would look something like this:
x = 1:18;
y = randn(1,18);
mask = y > 0;
y1 = y;
y1(mask) = nan;
bar(x,y1,'FaceColor','red')
hold on
y2 = y;
y2(~mask) = nan;
bar(x,y2,'FaceColor','green')
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/172494/image.png)
3 个评论
Mike Garrity
2016-1-13
Yeah, that's on our list, but I'm afraid it's not very close to the top of the list.
更多回答(1 个)
Star Strider
2016-1-13
编辑:Star Strider
2016-1-13
This seems to work, at least on my test data:
x = 1:10; y = randi([-9 9], 1, 10);
yp = y>0; % Logial Indices: Positive ‘y’ yn = y<0; % Logial Indices: Negative ‘y’ cm = [0.5 0.5 0.5; 0 0 0]; % Colour Matrix
figure(1) bar(x(yn), y(yn), 'FaceColor',cm(1,:)) hold on bar(x(yp), y(yp), 'FaceColor',cm(2,:)) hold off set(gca, 'XTick', x)
![](/matlabcentral/answers/uploaded_files/43348/Colouring%20Bars%20by%20'Y'%20value%20-%202016%2001%2013.png)
2 个评论
另请参阅
类别
在 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!