overlay bar plot without mixing color

6 次查看(过去 30 天)
piepsi
piepsi2021-11-8
评论: piepsi ,2021-11-8
I would like to create a bar plot with overlaying bars of different colours.
I tried using FaceAlpha but this alters the colours.
Basically, I would like my plot to look like a stacked bar colour wise, but like an ovelayed bar in terms of the values.
This is the simplified code and result of what I have tried:
A = [1;5;3;7;4];
B = [3;2;4;8;2];
figure;
bar(A, 'FaceColor', 'b', 'FaceAlpha',0.5)
hold on
bar(B, 'FaceColor', 'y', 'FaceAlpha',0.5)
hold off
How can I overlay my bars in a way that they show the colour I defined instead of mixing them to this weird muddy green in the overlaying bits?

采纳的回答

Rik
Rik 2021-11-8
Here is my solution, which allows you to specify the 3 face colors separately:
A = [1;5;3;7;4];
B = [3;2;4;8;2];
shared=min(A,B);
A_high=max(0,A-shared);
B_high=max(0,B-shared);
data=[shared A_high B_high];
h=bar(data,'stacked');
h(1).FaceColor='g';
h(2).FaceColor='b';
h(3).FaceColor='y';
  3 个评论
piepsi
piepsi 2021-11-8
I figured it out! Thank you for your help.
Here's the code for anyone having a similar problem:
A = [1;5;3;7;4];
B = [3;2;4;8;2];
shared = min(A,B);
A_high = max(0,A-shared);
B_high = max(0,B-shared);
A_low_idx = find(A<B);
B_low_idx = find(A>B);
A_idx_low = [A_low_idx(:); B_low_idx(:)];
B_idx_low = [B_low_idx(:); A_low_idx(:)];
zero = zeros(numel(A));
A_low = [A(A_low_idx); zero(B_low_idx)];
B_low = [B(B_low_idx); zero(A_low_idx)];
[A_idx_low, A_ids_low] = sort(A_idx_low);
[B_idx_low, B_ids_low] = sort(B_idx_low);
A_low = A_low(A_ids_low);
B_low = B_low(B_ids_low);
data = [A_low B_low A_high B_high];
h = bar(data,'stacked');
h(1).FaceColor = 'b';
h(2).FaceColor = 'y';
h(3).FaceColor = 'b';
h(4).FaceColor = 'y';

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by