Colours for different bar groups

35 visualizzazioni (ultimi 30 giorni)
Anne
Anne il 20 Dic 2017
Commentato: Anne il 20 Dic 2017
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 Commento
Anne
Anne il 20 Dic 2017
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.

Accedi per commentare.

Risposta accettata

Jos (10584)
Jos (10584) il 20 Dic 2017
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 Commenti
Jos (10584)
Jos (10584) il 20 Dic 2017
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 il 20 Dic 2017
Thank you for the explanation!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by