Bar Chart with different colors - Dependent on a additional information

2 次查看(过去 30 天)
Hello!
I've created this bar chart and now like to colour different values with different colours depending on the type to which they belong.
Every y-value has an additional information from which type the value is,
e.g. first value - type 1,
second value - 2,
third value - 1
fourth - 3
My suggestion was:
figure
hold on
for i = 1:length(l)
h = bar (y)
if l(i) == 1
set (h, 'Facecolor', 'k')
elseif l(i) == 2
set (h, 'Facecolor', 'r');
else
set (h, 'Facecolor', 'b');
end
end
y is the array with all the y-values and
l is the array containing all the types (already in the right order).
So the two arrays have the same size.
But the result won't be in different colours.
Can anyone help?
Sophia
  3 个评论
Mehmed Saad
Mehmed Saad 2020-4-3
define x axis for bar
figure,bar(1:10,100*rand(1,10),'Facecolor','k')
hold on,bar(11:20,100*rand(1,10),'Facecolor','b')
Sophia Bitterwolf
The problem is, that it's not that the first 10 values are type 1 (red) and the second 10 are type 2 (blue).
It can also happen that x-values 1-8 are type 1, 9 is type 2, 10-14 are type 3 and 15 is type 1 again.
So the type doesn't go in a ascending order.

请先登录,再进行评论。

采纳的回答

Ameer Hamza
Ameer Hamza 2020-4-3
编辑:Ameer Hamza 2020-4-3
This show how to make a bar chart with different colors based on a grouping variable. The reason for using a nan entry in the input array of bar function is explained here: https://www.mathworks.com/matlabcentral/answers/360978-fixing-the-absolute-bar-width-on-bar-plot
x = 1:10;
y = rand(1, 10);
grp = [1 2 2 3 3 3 2 1 1 2];
unique_grps = unique(grp);
colors = rand(numel(unique_grps), 3);
ax = axes();
hold(ax);
for i=1:numel(unique_grps)
mask = grp==unique_grps(i);
X = x(mask);
Y = y(mask);
b = bar([X X(end)+1], [Y nan], 0.7, 'FaceColor', colors(i,:));
end
  7 个评论
Ameer Hamza
Ameer Hamza 2020-4-3
Sophia, yes you are correct. I forgot to specify the color in the bar statement. Check the updated code.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by