Changing transparency of individual bars in bar

63 次查看(过去 30 天)
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?

采纳的回答

Adam Danz
Adam Danz 2020-9-25
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 个评论
Lorcan Conlon
Lorcan Conlon 2020-9-25
reordercats doesn't appear to work with duplicated values however. Is there a way around this?
Adam Danz
Adam Danz 2020-9-25
编辑:Adam Danz 2020-9-25
You shouldn't duplicate anything in the 'neworder' vector. My last comment says "do not override the categorical name until after reordering".
So,
  1. Define the categorical values: bounds=categorical({'aa','bb','cc','dd','ee'});
  2. Do the reordering: bounds=reordercats(bounds,{'aa','bb','cc','dd','ee'});
  3. 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,
  1. Define the categorical values: bounds=categorical({'aa','bb','cc','dd','ee'});
  2. Switch cc to bb before reordering
  3. 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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by