MahD
MahD

Reputation: 77

Change the color of bar element in Matlab bar graph?

how can I change the color of one of my bar element in the bar graph? Because it seems my Matlab version (2015b) doesn't let me use either b.LineWidth b.EdgeColor Or CData. my code is something like below;

b = bar(1:30); 
b.FaceColor = 'flat'; 
[bv,bi] = max(1:30); 
b(bi).LineWidth = 2;
b(bi).EdgeColor = 'red';

With this error for using b.LineWidth and b.EdgeColor;

No public property LineWidth exists for class matlab.graphics.GraphicsPlaceholder. Error in tt (line 5)

and the error for using CData;

b = bar(1:30); 
b.FaceColor = 'flat'; 
[bv,bi] = max(1:30);
b.CData(bi) = [0.4,0.4,0.4];

No appropriate method, property, or field 'CData' for class 'matlab.graphics.chart.primitive.Bar'.

Upvotes: 1

Views: 2234

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60504

(I just learned something new today!)

It seems that bar has two main modes of operation, producing different handle graphics object types. The style input argument selects the mode of operation:

  • bar(...,'grouped') or bar(...,'stacked') produces a Bar object. Note that grouped is the default style.

  • bar(...,'hist') or bar(...,'histc') produces a Patch object.

The documentation does not specify that the hist mode produces a different object type. In R2015b these same options existed, I presume the output types were the same as they are with my version of MATLAB (R2017a).

The Bar object produced by the first mode does not have a CData property. There is a FaceColor and EdgeColor property. See the Bar properties documentation for more information. But note that this is a single object, so you cannot index into the handle and set properties for individual bars. The properties control all bars at the same time:

b = bar(1:30); 
b.FaceColor = 'flat'; 
b.LineWidth = 2;
b.EdgeColor = 'red';

The exception is the XData and YData property, which have one value per bar.

The Patch object produced by the second mode does have a CData property. It's a bit more complex to manipulate, because the Patch has coordinates for each vertex and each edge. But the CData property can be set in different ways depending on your needs. Set to a Nx1 array (with N the number of bars) it gives an index into the color map for each bar (but see also the axis' Clim property for how that index is interpreted). Set to a Nx1x3 array it gives an RGB triplet for each bar. See the Patch properties documentation for more information. Here is an example:

b = bar(1:30,'hist'); 
b.FaceColor = 'flat'; 
b.LineWidth = 2;
b.EdgeColor = 'red';
cols = zeros(30,1,3)+0.5;
cols(5,1,:) = [1,0,0];
b.CData = cols;

[Credit to gnovice in this answer.]

Upvotes: 2

Related Questions