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

8 ビュー (過去 30 日間)
Abhinav
Abhinav 2024 年 9 月 9 日
コメント済み: Abhinav 2024 年 9 月 9 日
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 Center および File ExchangeBar Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by