Colours for different bar groups

35 次查看(过去 30 天)
Hello, I'm having problems to plot my data as a bar graph, with different colours for the different bar groups. I've read a bit about setting colours for bars, and that you would have to plot them individually to do so: https://se.mathworks.com/matlabcentral/answers/uploaded_files/59506/barchart.m
The problem is that I want to plot multiple bars grouped together in one plot, as automatically done when you have your data in a matrix. That looks like this and is almost the way I want it (but has the wrong colours):
Data(1,1)= 0.91;
Data(1,2)= 0.91;
Data(2,1)= 0.65;
Data(2,2)= 0.79;
barh(Data,1)
ylabel('gradient [permil]');
set(gca,'yticklabel',{'Control','Gas'});
set(gca,'YTickLabelRotation',90);
The first set is Data is duplicated because I actually have groups of different sizes and matlab doesn't allow that (but that's another problem). It would be fine for me to make one wide black bar out of this first set. So I would want to make the first two bars black, and the second two another colour, etc. (I will add more data). I tried doing this, but then the bars are plotted over one another:
mydata=Data;
figure(1)
hold on
a=1
for i = 1:length(mydata(a,:))
h=barh(i,mydata(i,a));
if i == 1
set(h,'FaceColor','black');
elseif 1 == 2
set(h,'FaceColor','blue');
else
set(h,'FaceColor','red');
end
a=a+1;
end
hold off
This seperation into groups goes automatically in my first example, as I use a matrix. I just can't figure out how to do it when I plot them stepwise to get a handle on the colours. I hope you can help! Thank you
  1 个评论
Anne
Anne 2017-12-20
Hello, I figured out one way where I just plot a new bar over my old bars, which then also solves my problem with the different sizes of the groups.
h=barh(Data,1);
hold on
h(1).FaceColor = 'r';
h(2).FaceColor = 'b';
%here I plot my first bar over the wrongly-coloured first 2 bars
h=barh(Data(1,1));
h(1).FaceColor = 'k'; %now I can pick the color, yay!
hold off
If you know of a more elegant way, please tell me.

请先登录,再进行评论。

采纳的回答

Jos (10584)
Jos (10584) 2017-12-20
data = [0.91 NaN 0.65 0.79]
% the stacked trick
H = barh(1:numel(data), diag(data),'stacked')
H(1).FaceColor = 'k' ; % set the colour of one bar
  3 个评论
Jos (10584)
Jos (10584) 2017-12-20
Hi Anne,
diag(data) creates a matrix where each column is plotted as a separate stacked bar. But because there are zeros in there, you don't see them
barh(diag(data)+1) % reveals the trick
There are some drawbacks of this too. You cannot set the width of an individual bar, for instance.
Anne
Anne 2017-12-20
Thank you for the explanation!

请先登录,再进行评论。

更多回答(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