MATLAB: Changing transparency of individual bars in bar

bar plot

I am trying to plot a 2D bar plot where I want to be able to control the transparency of individual bars. My code is as follows
bounds=categorical({'aa','bb','cc','dd','ee'});
bounds=reordercats(bounds,{'aa','bb','cc','dd','ee'});
%set(bounds,'Interpreter','latex');
legend('$\hat{\psi}$','Interpreter','latex')
vals=[1,2,3,4,5]
b=bar(bounds,vals);
b.FaceColor = 'flat';
b.CData(1,:) = [0 0 1];
b.CData(2,:) = [1 0 0];
b.CData(3,:) = [1 0 0];
b.CData(4,:) = [0 1 0];
b.CData(5,:) = [0 1 0];
b.AlphaData(1,:)=0.2
%b(1).FaceAlpha=0.2;
b.LineStyle=':';
I have tried two lines at the bottom using b.AlphaData and b(1).FaceAlpha, but these do not have the desired effect. The first gives an error and the code stops, whereas the second changes the transparency of all the bars simultaneously. Is there a way that I can for example set the 2nd and 4th plots to be transparent (e.g. 0.3) and have dotted outlines, while not changing bars 1, 3 and 5?

Best Answer

You can plot the bars one at a time or in groups that all have the same FaceAlpha level.
That way the bars with differen alpha levels are independent and have their own properties.
Demo:
bounds=categorical({'aa','bb','cc','dd','ee'});
bounds=reordercats(bounds,{'aa','bb','cc','dd','ee'});
%set(bounds,'Interpreter','latex');
% legend('$\hat{\psi}$','Interpreter','latex')
vals=[1,2,3,4,5];
colors = [0 0 1;
1 0 0;
1 0 0;
0 1 0;
0 1 0];
alphas = linspace(.08,.9, numel(bounds));
b = gobjects(size(bounds));
cla()
hold on
for i =1:numel(bounds)
b(i)=bar(bounds(i),vals(i));
set(b(i),'FaceColor',colors(i,:),'FaceAlpha',alphas(i));
end
grid on
Related Question