问题
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.
回答1:
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')
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))
回答2:
You can achieve what you are looking for like this:
b = bar([rand(1,3);nan(1,3)],'b');
b(2).FaceColor = 'r';
You can also achieve this by calling the bar function multiple times with different values (which is a practice that you may need to use sometimes):
A = [1,2,3,4,1,3,2];
bar([1],A(1),'FaceColor','r');
bar([2:4],A(2:4),'FaceColor','g');
bar([5:7],A(5:7),'FaceColor','b');
来源:https://stackoverflow.com/questions/47281603/matlab-bar-no-public-property-cdata-exists