This issue has been resolved in MATLAB R2017b with the addition of a property "CData" to the "bar" function. To find out more about "CData", look at the following documentation page.
Prior to MATLAB R2017b, there was no built in function in MATLAB to control the color of individual bars in the bar graphs, but you can plot each bar individually and set the colors one at a time. For example:
for i = 1:length(mydata)
if mydata(i) < 0.2
elseif mydata(i) < 0.6
will produce a figure similar to the one below:
In MATLAB R2014a and earlier, the following example provides an alternative method to set the color of a bar in the chart based on its value.
First, obtain the handle to the 'Children' of a bar graph.
1. In order to map the color on the bars to your data, execute the following code:
Once 'CData' is set to "mydata", the colors on the individual bars are decided by comparing their values linearly with the default colormap "jet". You can change the colors on your barplot now by changing the colormap to one of the supplied colormaps. For example,
2. Since the default colormap is "jet", the minimum value in "mydata" is mapped to blue and the maximum value in "mydata" is mapped to red. To have more control on the colors on the bar, create your own colormap
mycolor=[0 0 0;0 0 1;1 0 0];
This will create a colormap with black as the first color, blue as the second, and red as the third color. Applying this colormap forces the color of the bars in the chart to be dependent on a linear scale between "mydata" and the number of available colors in the colormap. So the first third of the data range is black, the second third is blue, and the final third is red.
3. To apply specific colors for specific data ranges, set the 'CDataMapping' property to 'direct'.
For example, to map all values between [0, 0.2) to black, all values between [0.2, 0.6) to blue, and all values between [0.6, 1] to red, execute the following code:
mycolor=[0 0 0;0 0 1;1 0 0];
Set the 'CData' to the desired indices of the colormap.
As an alternative to looping through the data, apply a vectorized method using logical arrays. In the following example, a logical array is found for a specific data range, and then wieghted by the color index associtated with the data range. The sum of the weighted logical arrays will result in the index vector.
blackRange = 1*(mydata<0.2);
redRange = 3*(mydata>=0.6);
blueRange = 2*~(blackRange+redRange);
index = blackRange + redRange + blueRange;
4. Note that if you have more than 150 datapoints to plot, you may see an error similar to the following after setting the 'CData' property: ERROR: Warning: Patch FaceVertexCData length (160) must equal Vertices length (801) for flat EdgeColor
In that case, you will need to set the 'EdgeColor' property of the 'bar_child' to a color specification or to 'none'. Add the following line just before the command that sets the 'CData' property:
set(bar_child, 'EdgeColor', 'r');