How to colour each individual bar with a different colour?

I would like to colour each individual bar with a different colour. Any assistance, please?
My example below:
CoverageArea = [101.1303,0,114.9316,45.2112,116.5973,95.8953];
bar(CoverageArea)
ylabel('Coverage area (m²)');
xticklabels({'\Phi_1_/_2 = 15, (\phi & \psi) =\pm 10','\Phi_1_/_2 = 15, (\phi & \psi) =\pm 40','\Phi_1_/_2 = 30, (\phi & \psi) =\pm 10','\Phi_1_/_2 = 30, (\phi & \psi) =\pm 40','\Phi_1_/_2 = 60, (\phi & \psi) =\pm 10','\Phi_1_/_2 = 60, (\phi & \psi) =\pm 40'})
grid on;

 채택된 답변

Voss
Voss 2022년 11월 11일
CoverageArea = [101.1303,0,114.9316,45.2112,116.5973,95.8953];
h = bar(CoverageArea);
ylabel('Coverage area (m²)');
xticklabels({'\Phi_1_/_2 = 15, (\phi & \psi) =\pm 10','\Phi_1_/_2 = 15, (\phi & \psi) =\pm 40','\Phi_1_/_2 = 30, (\phi & \psi) =\pm 10','\Phi_1_/_2 = 30, (\phi & \psi) =\pm 40','\Phi_1_/_2 = 60, (\phi & \psi) =\pm 10','\Phi_1_/_2 = 60, (\phi & \psi) =\pm 40'})
grid on;
colors = get(gca(),'ColorOrder') % use whatever colors you want here
colors = 7×3
0 0.4470 0.7410 0.8500 0.3250 0.0980 0.9290 0.6940 0.1250 0.4940 0.1840 0.5560 0.4660 0.6740 0.1880 0.3010 0.7450 0.9330 0.6350 0.0780 0.1840
set(h,'FaceColor','flat','CData',colors(1:6,:)) % set the bars' colors

댓글 수: 4

@Voss Thank you very much dear. I accepted your answer. If you do not mind, may you exaplain how they work these two lines?
colors = get(gca(), 'ColorOrder' ) % use whatever colors you want here
set(h, 'FaceColor' , 'flat' , 'CData' ,colors(1:6,:)) % set the bars' colors
You're welcome my friend.
Sure, the first line
colors = get(gca(), 'ColorOrder' )
is there to create an n-by-3 matrix of doubles, each row of which will be used as a color [R G B] in the next line. I'm using the current axes 'ColorOrder', but you can specify whatever colors you want, e.g.:
colors = [ ...
0 0 0; ... % black
1 0 0; ... % red
0 1 0; ... % green
0 0 1; ... % blue
0 1 1; ... % cyan
1 0 1; ... % magenta
1 1 0; ... % yellow
1 1 1; ... % white
];
The second line modifies the bar object such that each bar's color is set to one row of colors. Make sure colors has at least as many rows as you have bars. The (1:6,:) takes just the first 6 rows of colors, since there are 6 bars in this case.
@Voss I really appreciate your kindness.
You're welcome!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

태그

질문:

2022년 11월 11일

댓글:

2022년 11월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by