how to color each individual bar a different color on my bar graph with my labels?

5 Ansichten (letzte 30 Tage)
There are five bars in my bar graph and each represent a color. I would like to code my graph to match the color the bar represents
%code
c=categorical({'red','green','blue','yellow','orange'}) %x-axis
occupied= [97 82 75 88 69]; %y-axis
figure
bar(c,occupied)
title('Parking Occupency')
xlabel('Decal')
ylabel('Closed Parking')

Antworten (1)

Astha Singh
Astha Singh am 14 Dez. 2018
Hi,
This can be done in the following two ways,
(1) By updating the 'CData' (color data) of the bar plot.
For multiple bars, color data is a three-column matrix. Each row in the matrix specifies an RGB triplet for a particular bar. , The RGB triplet is in the range: (0,1) and has to be explicitly provided. Please refer the example code provided below::
%Define the colors' RGB values in a matrix
col(1,:) = [1 0 0]; % -- red
col(2,:) = [0 1 0]; % -- green
col(3,:) = [0 0 1]; % -- blue
col(4,:) = [1 1 0]; % -- yellow
col(5,:) = [255 165 0]/255; % -- orange
c=categorical({'red','green','blue','yellow','orange'}); %x-axis
%The following is done to let the x-axis variables remain in the specified order, as
%categoricals can have order associated with them (for the purpose of relational operators)
c = reordercats(c,{'red','green','blue','yellow','orange'});
occupied= [97 82 75 88 69]; %y-axis
figure
occupied= [97 82 75 88 69]; %y-axis
b=bar(c,occupied,'FaceColor','flat');
b.CData = col;
title('Parking Occupency')
xlabel('Decal')
ylabel('Closed Parking')
(2) The second method to achieve the desired behaviour, is to plot each bar separately in a loop, while defining the 'FaceColor' property for each. The following sample code shows how that can be done:
%Define the colors' RGB values in a matrix
col(1,:) = [1 0 0]; % -- red
col(2,:) = [0 1 0]; % -- green
col(3,:) = [0 0 1]; % -- blue
col(4,:) = [1 1 0]; % -- yellow
col(5,:) = [255 165 0]/255; % -- orange
c=categorical({'red','green','blue','yellow','orange'}); %x-axis
occupied= [97 82 75 88 69]; %y-axis
figure
current_bar = bar(c(1),occupied(1),'FaceColor',col(1,:));
hold on;
for i=2:length(c)
bar(c(i),occupied(i),'FaceColor',col(i,:))
end
title('Parking Occupency')
xlabel('Decal')
ylabel('Closed Parking')

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by