How to control color of each bar (all stacks same color) in stacked bar chart?
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Jatin
le 9 Sep 2024
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:
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Bar Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!