How to change the color of individual bars in a bar chart?

298 ビュー (過去 30 日間)
the cyclist
the cyclist 2016 年 10 月 31 日
編集済み: Scott MacKenzie 2021 年 4 月 18 日

Make a simple bar chart (and get its handle):

figure
rng default
hb = bar(rand(1,3));

How can I set the colors of those bars now (after I have made the figure)? I want each bar to be a different color.

I am specifically asking about MATLAB R2016b.

I asked a very similar question about MATLAB R2014b earlier, but that method no longer seems to work. (Or I am overlooking something again.

採用された回答

Image Analyst
Image Analyst 2016 年 11 月 1 日
編集済み: Image Analyst 2016 年 11 月 1 日
See attached demo.
Sorry - it's basically the same as what Sean did, just fancier and more flexible. You could put a wrapper around it to make it easier to use though.

その他の回答 (4 件)

Scott MacKenzie
Scott MacKenzie 2021 年 4 月 18 日
編集済み: Scott MacKenzie 2021 年 4 月 18 日
Here's a simple solution. Notably, all the bar colors are set in a single statement (provided the new colors are pre-defined in a matrix).
x = 1:3;
y = randi(100,1,3);
clr = [223 145 167;
178 198 65;
134 156 211] / 255;
b = bar(x, y, 'facecolor', 'flat');
b.CData = clr;

Dr. Murtaza Ali Khan
Dr. Murtaza Ali Khan 2019 年 3 月 16 日
編集済み: Dr. Murtaza Ali Khan 2019 年 3 月 16 日
mydata=rand(1,10)
color= ['r','g','b','k'];
figure, hold on
% % if data is more than colors then colors will be repeated
m = length(color);
for k = 1:length(mydata)
i = mod(k-1,m); %%i is remainder after division of k-1 by m
i = i+1;
h=bar(k,mydata(k));
set(h,'FaceColor',color(i));
end

Sean de Wolski
Sean de Wolski 2016 年 10 月 31 日
Why not just make a second bar?
y = rand(1,3);
hb = bar(y);
hold on
hbr = bar(2,y(2),'r');
  2 件のコメント
the cyclist
the cyclist 2016 年 11 月 1 日
I appreciate the answer, but ...
Ugh. Let's hope there is a way to do this via the properties of one bar chart, rather using N bar commands for an N-bar chart.
Sean de Wolski
Sean de Wolski 2016 年 11 月 1 日
I don't know of a way to do it using documented properties. You can trick bar into returning a bar array by padding with NaNs but then you need to deal with limits and ticks yourself all while still creating more bars so it's not saving you anything but is adding more headache.
b = bar([rand(1,3);nan(1,3)],'b')
b(2).FaceColor = 'r'
Which is why calling bar a few times is really not the end of the world. It's not like with a line where there could be millions of points so you're going to chew up data to plot duplicate lines. Most figures will only have less than few dozen bars total.
All of this said, I think it's a fair enhancement request to have an option to get back a handle to each bar separately.

サインインしてコメントする。


Yaser Khojah
Yaser Khojah 2019 年 10 月 21 日
how would you show the legend color here?

カテゴリ

Help Center および File ExchangeBar Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by