Color specific bars in a histogram

29 views (last 30 days)
Bill
Bill on 29 May 2013
Commented: Marcin Petela on 30 Mar 2022
Hello everyone,
I'm hoping someone can help me solve a problem I seem to be struggling with. I am using the hist and bar functions to plot an event timeline for a study. Basically, the X-axis for my histogram is time, with the Y-axis being the number of events that occur in that bin. Due to the nature of my task, some events occur in the same timeline as other events, so it would be helpful to have those noted in a different color, etc. What I would like to do is be able to specify what bars or bins that are rendered in the histogram appear in what color.
Currently I've tried both the 'facecolor' and 'facevertexcdata' properties, both of which don't seem to work 100%. 'facecolor' seems to not be able to let me specify what bins to assign, and 'facevertextcdata' does allow me to specify what bins to show, but for whatever reason, when the X-axis is long, and there are a number of bars in the histogram (20 or so), the bars fail to render when the 'facevertexcdata' property is applied.
Attached you'll find a bit of code which I'm hoping can better explain my point.
x = handles.minTime:handles.histogramInterval:handles.maxTime;
y = sort(Randi(1500, [1, 30]));
handles.histogramFigure = figure;
figure(handles.histogramFigure);
[YAxisValue binCenters] = hist(y, x);
handles.BarPlot = bar(binCenters, YAxisValue, 'hist');
I already no that certain elements in y (y(2), y(5), y(13), etc.) are of a different event type. What I need is to render the bars of those events in a different color than the default blue.
Any and all suggestions would be greatly appreciated. Thanks so much for your time.
Bill

Answers (1)

Eldwin Cheung
Eldwin Cheung on 6 Feb 2020
bump. would love to see an answer to this as well. hello from 2020.
  2 Comments
Davide Menzio
Davide Menzio on 15 Dec 2020
I found the answe today:
convert your histogram into a bar plot:
n = [4,2,2,2,2,2,2,3,2,6,4,2,2,3];
h = histogram(n);
b = bar(2:6,h.Values);
b.FaceColor = 'flat';
b.CData(2,:) = [.5 0 .5];
in this way you will color only the second bar differently.
Hope it helps

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!