필터 지우기
필터 지우기

Colours for different bar groups

조회 수: 46 (최근 30일)
Anne
Anne 2017년 12월 20일
댓글: Anne 2017년 12월 20일
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에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by