change colors for each bins in histogram

8 ビュー (過去 30 日間)
bero
bero 2016 年 2 月 28 日
編集済み: Marion Baques 2022 年 2 月 2 日
Hi, I have attached sample data, I plot histogram for the sample data as: hist = histogram(sample)
I need to color each bin(group of values) in different, and put annotation text in figure what each color represent :
  2 件のコメント
Walter Roberson
Walter Roberson 2016 年 2 月 28 日
Which MATLAB version are you using? This task got more difficult as of R2014b.
bero
bero 2016 年 2 月 28 日
matlab R2015a

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

採用された回答

Walter Roberson
Walter Roberson 2016 年 2 月 28 日
From R2014b onwards, the only way to do it is to bar() in each entry one at a time, specifying the color you want. Well, you could also use patch() or fill() or rectangle() to put in the bars; the point is that histogram objects do not allow you to change the bar colors individually now.
  1 件のコメント
bero
bero 2016 年 2 月 28 日
Could you please do it for 2 entry with the annotation text??in any sample example... Thx

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

その他の回答 (1 件)

Srivathsan Iyengar
Srivathsan Iyengar 2019 年 12 月 5 日
編集済み: Srivathsan Iyengar 2019 年 12 月 5 日
One way to do it is to overlay multiple histogram plots on the same axes, one plot for each bin. This makes sense for reasonable number of bins, not for large number of bins.
Here's an example code:
load sample.mat;
xValues = unique(sample);
binColors = [repmat(reshape(repmat(0:0.5:1,9,1),27,1),1,1) repmat(reshape(repmat(0:0.5:1,3,1),9,1),3,1) repmat(reshape(repmat(0:0.5:1,1,1),3,1),9,1)];
hf = figure; hax = axes; hold on;
legendStr = cell(1,length(xValues));
for i=1:length(xValues)
histogram(hax, sample(sample == xValues(i)), 'FaceColor',binColors(i,:));
legendStr(i) = {num2str(xValues(i))};
end
legend(legendStr);
  5 件のコメント
Charmi Patel
Charmi Patel 2022 年 2 月 1 日
Hello Marion,
Thank you for your solution. It was really helpful to me. But I get an error on the line colormap('jet',56) on R2021b version that first argument must be scalar axes or figure handle. Can you please confirm which version are you using? Also it would be great if you have some solution to this
Thanks!
Marion Baques
Marion Baques 2022 年 2 月 2 日
Hello Charmi,
I think the error comes from the way the colormap function is written. It is my mistake as I use the crameri colorscale (scientific colorscale). If you write "colormap(jet(56))", it works. I tried for me and it is working the same.
Hope this solves your problem!

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by