Search code examples
matlabcolorshistogrammatlab-figure

Coloring Bars from a histogram/bargraph


I'm currently working on a project. For this project I've binned data according to where along a track something happens and now I would like to nicely present this data in a histogram. For this data however, multiple environments have been presented. I would like to color code each environment with its own color. The way I've done it now (very roughly) is:

x = 0:1:10;
y = bins;
color = ['b', 'g', 'g', 'g', 'y', 'y', 'g', 'g', 'g', 'b'];
b = hist(x, y, 'facecolor', 'flat');
b.CData = color

In this data bins contains all the bins a freeze has happened (1-10). These numbers are not in chronological order and not all numbers are present. However, when i use the code i get the following error:

Unable to perform assignment because dot indexing is not supported for variables of this type.

How can I color my various bars?


Solution

  • This is very nearly a duplicate of this question:

    How to draw a colorful 1D histogram in matlab

    However, you want to specify the colours according to the colorspec letter which changes things slightly.

    The general concept is the same; you don't have that level of control with either hist (which is deprecated anyway) or histogram, so you have to plot it in two steps using histcounts and bar, because you do have that level of control on bar plots:

    x = randn(100,1)*10; % random example data
    
    % Specify the colours as RGB triplets 
    b = [0, 141, 201]/255;
    g = [0, 179, 9]/255;
    y = [247, 227, 40]/255;
    % Build the numeric colours array
    color = [b; g; g; g; y; y; g; g; g; b];
    
    % Plot using histcounts and bar
    [h,edges] = histcounts(x,10); % calculate the histogram data. 10 = size(color,1)
    b = bar( (edges(1:end-1)+edges(2:end))/2, h ); % plot the bar chart
    b.BarWidth = 1; % make the bars full width to look the same as 'histogram'
    b.CData = color; % color is a 10x3 array (columns are RGB, one row per bar)
    b.FaceColor = 'flat';   % Make 'bar' use the CData colours
    

    plot

    Tip: you can find RGB colour values easily using any number of colour pickers online, but Googling "color picker" will give you one at the top of Search, from which you can copy the RGB values. Note that MATLAB expects values between 0 and 1, not 0 and 255.