Search code examples
matlabcolorsmatlab-figure

Matlab: bar No public property CData exists


The Matlab example code cannot run in Matlab 2017a (Linux 64bits): https://cn.mathworks.com/help/matlab/ref/bar.html

b = bar(rand(10,1));
b.FaceColor = 'flat';
b.CData(2,:) = [.5 0 .5];

It can not color the specific bar and warns as:

No public property CData exists for class matlab.graphics.chart.primitive.Bar.

I don't know it is a specific feature merely for Matlab 2017b?

This code is only to color the specific bar. In Matlab 2012a, it can be easily done by:

bh=bar(MyStem); h=get(bh, 'children');
shading flat;  set(h,'FaceVertexCData',MyColor);

I cannot understand why Matlab 2017 removes this feature.


Solution

  • About the CData property, I wrote already in the comment. Anyway, another workaround that I think can be more simple than those that been suggested, can be that:

    x=rand(1,10);
    b=bar([x;zeros(1,length(x))]);
    xlim([0.5 1.5])
    set(b,'FaceColor','r')
    set(b(2),'FaceColor','b')
    

    enter image description here

    If you want to number the bars as in a regular bar graph, you can add this:

    set(gca,'XTick',0.5+[b.XOffset])
    set(gca,'XTicklabels',1:length(x))
    

    enter image description here