How to color each group of a bar plot into a different color

49 vues (au cours des 30 derniers jours)
priyam kar
priyam kar le 8 Déc 2023
Commenté : Dyuman Joshi le 8 Déc 2023
I have a bar plot with 16 groups with each group having 3 bars. I want to color each group of bar plot into a different color. Someone please help me out with this.

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 8 Déc 2023
%Random data
mat = randi(20, 16, 3);
%Plot bar graph
b = bar(mat);
n = size(mat,1);
%Get color for each group
color = hsv(n);
%Change the color for each group
for k=1:size(mat,2)
b(k).FaceColor = 'flat';
b(k).CData = color;
end
  2 commentaires
priyam kar
priyam kar le 8 Déc 2023
Thanks again for your help, this worked perfectly
Dyuman Joshi
Dyuman Joshi le 8 Déc 2023
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (1)

Adam Danz
Adam Danz le 8 Déc 2023
Modifié(e) : Adam Danz le 8 Déc 2023
h=bar(x,'grouped') where x is an n by m matrix, will create a bar chart with n groups that each have m bars. h will be a 1xm matrix of bar handles.
To apply a color to each group, create a n by 3 matrix of RGB color values that defines the color for each group. Then apply the color matrix to the CData property of each bar object (R2017b or later). You'll also need to set FaceColor to flat.
rng default
data = rand(16,3);
b = bar(data, 'grouped');
colors = rand(height(data),3);
for i = 1:numel(b)
b(i).FaceColor = 'flat';
b(i).CData = colors;
end
  1 commentaire
Dyuman Joshi
Dyuman Joshi le 8 Déc 2023
@Adam Danz, this works without providing the 'grouped' argument as well.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Discrete Data Plots dans Help Center et File Exchange

Tags

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by