How to control color of each bar (all stacks same color) in stacked bar chart?
8 次查看(过去 30 天)
显示 更早的评论
I have a bar chart with multiple stacks. I would like to represent all stacks of same bar with same color, while changing colors across bars. Is this possible? In the figure below, I would like bars 4, 3, 2, 1 to be of different colors but the stacks within one bar to be same. (My goal is to represent timeline of events using bar command)
data_with_init_time = [
1, 10, 5, 3 ;
3, 10, 3, 9 ;
7, 10, 4, 8 ;
12,10, 2, 2 ];
h = barh(data_with_init_time, 'stack');
0 个评论
采纳的回答
Jatin
2024-9-9
If we go through the documentation for the 'FaceColor' property of a 'barh' object, we see that the 'FaceColor' must be set to 'flat' to apply custom colors. The coloring is controlled through the "CData" property of the bar object, where you can specify custom colors using RGB triplets. Below is a sample code that assigns the same color to all stacks within a bar:
data_with_init_time = [
1, 10, 5, 3;
3, 10, 3, 9;
7, 10, 4, 8;
12,10, 2, 2 ];
% Create a stacked bar chart
h = barh(data_with_init_time, 'stacked');
% Define colors for each bar in RGB
colors = [1 0 0;0 1 0;0 0 1;0 1 1];
% Loop through each bar stack
for i = 1:size(data_with_init_time, 1)
for j = 1:length(h) % Loop through the stacks
h(j).FaceColor = 'flat'; % Use flat coloring
h(j).CData(i,:) = colors(i, :); % Assign the same color to all stacks of the same bar
end
end
Kindly go through the documentation of 'FaceColor' for more details:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Bar Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!