how to color each individual bar a different color on my bar graph with my labels?
5 ビュー (過去 30 日間)
古いコメントを表示
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')
0 件のコメント
回答 (1 件)
Astha Singh
2018 年 12 月 14 日
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')
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!