How to control color of each bar (all stacks same color) in stacked bar chart?

조회 수: 7 (최근 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');

채택된 답변

Jatin
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 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