Changing transparency of individual bars in bar
74 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Adam Danz
on 25 Sep 2020
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
6 Comments
Adam Danz
on 25 Sep 2020
Edited: Adam Danz
on 25 Sep 2020
You shouldn't duplicate anything in the 'neworder' vector. My last comment says "do not override the categorical name until after reordering".
So,
- Define the categorical values: bounds=categorical({'aa','bb','cc','dd','ee'});
- Do the reordering: bounds=reordercats(bounds,{'aa','bb','cc','dd','ee'});
- Now switch the cc to bb
There are lots of ways to do that. The method in my answer is just to demonstrate the main idea so you can take it from there. For example, you could do,
bounds(3) = categorical({'bb'});
but now an empty space will appear in the bar plot where cc should go.
Another method is,
- Define the categorical values: bounds=categorical({'aa','bb','cc','dd','ee'});
- Switch cc to bb before reordering
- Do the reordering but don't include cc: bounds=reordercats(bounds,{'aa','bb','dd','ee'});
Now there won't be any empty spaces in the bar plot for cc.
More Answers (0)
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!