2

I want to color the bars in a MATLAB barplot as suggested below in the out-commented part of my code, however, when this part is included, it is throwing an error. How could I solve this?

x = [1.5,2.5;1.5,2.5;1.5,2.5];

b = bar(x)
% b.FaceColor = 'flat';
% b.CData(1,:).FaceColor = [0.4,0.6,0.8];        
% b.CData(2,:).FaceColor = [0.3,0.4,0.6];  


set(gca,'XTickLabel',{'\fontsize{16}Cond1', '\fontsize{16}Cond2', '\fontsize{16}Cond3'})

legend('\fontsize{16}Class1','\fontsize{16}Class2');
ylim([0 5.5])
ylabel('\fontsize{16}Intensities [V]')
title('\fontsize{16}Intensities for all conditions');
Pugl
  • 432
  • 2
  • 5
  • 22

3 Answers3

2

You probably try to use the new property CData of bar function, while you using a former version of matlab. If you get the error that you wrote in the comments (why not in the question itself?), you should just omit the CData:

x = [1.5,2.5;1.5,2.5;1.5,2.5];
b = bar(x)

enter image description here

b(1).FaceColor = [0.4,0.6,0.8];
b(2).FaceColor = [0.3,0.4,0.6];

enter image description here

Adiel
  • 3,071
  • 15
  • 21
1

The following two lines don't look right:

b.CData(1,:).FaceColor = [0.4,0.6,0.8];
b.CData(2,:).FaceColor = [0.3,0.4,0.6];

You're looking for:

b.CData(1,:) = [0.4,0.6,0.8];
b.CData(2,:) = [0.3,0.4,0.6];
frslm
  • 2,969
  • 3
  • 13
  • 26
  • so, adding b.CData(1,:) = [0.4,0.6,0.8]; b.CData(2,:) = [0.3,0.4,0.6]; is actually throwing me an error... – Pugl Oct 23 '17 at 22:25
  • Have you tried replacing the commas with spaces (e.g. `[0.4 0.6 0.8]`)? I think that does the same thing however. Alternatively, what error message are you getting? – frslm Oct 23 '17 at 22:28
  • No appropriate method, property, or field 'CData' for class 'matlab.graphics.chart.primitive.Bar'. Error in plotCorr (line 21) b.CData(1,:) = [0.4,0.6,0.8]; – Pugl Oct 24 '17 at 06:15
1

Please try that one:

x = [1.5,2.5;1.5,2.5;1.5,2.5];

b = bar(x);
b(1).FaceColor = [0.4,0.6,0.8];
b(2).FaceColor = [0.3,0.4,0.6];

I think it will do exactly what you want. Basically you need to index b object to get access to a different data set, and to change it's color you need to modify a FaceColor property.

pkic
  • 36
  • 4