Home > Enterprise >  Coloring Bars from a histogram/bargraph
Coloring Bars from a histogram/bargraph

Time:07-27

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?

CodePudding user response:

This is very nearly a duplicate of this question:

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.

CodePudding user response:

In R2007b b = hist() indeed outputs a 1x11 double array, being the counts in each bin. This means that you cannot use the regular syntax to output a figure handle that way. Citing the documentation:

n = hist(Y) bins the elements in vector Y into 10 equally spaced containers and returns the number of elements in each container as a row vector. (...)

Solution 1:

Call hist(__); b = get(gcf);, i.e. force a figure handle. Check its properties on where the CData-equivalent property is. (On R2007b you need to do b = get(gcf);, followed by set(b, 'Color', color))

Solution 2:

Use the nowadays recommended histogram(). You can check its property list, you need to set

b.FaceColor = color;
b.EdgeColor = color;

However, as is already noted in this question hist(), and also histogram(), do not natively support the handling of multiple colours. That means that either of the above tricks need to be applied on a per-colour basis. In other words: first plot everything you want to have the colour blue with histogram( __, 'FaceColor', 'b', 'EdgeColor', 'b'), then the same for the green graph etc.

  • Related