prevent shaded areas from changing the colors of the bars.

5 vues (au cours des 30 derniers jours)
David
David le 21 Oct 2021
Commenté : David le 21 Oct 2021
I am plotting a bar chart with shaded areas in the background. The shaded areas, however, cause my bars in the overlap area to change color. This is also true for other types of plots.
I am looking for an option for either the shaded areas or for my bar chart to keep the original color in the overlap area.
Here is a minimum example:
% some random numbers for bar plot.
T= 30;
x=randn(T,1);
x(x<0)=0;
% get maximum of x as upper bound for shaded area.
mymax = max(x);
myshadeU = zeros(T,1);
myshadeU(1:15) = repmat(mymax, T/2, 1);
myshadeL = zeros(T,1);
% shaded area.
fill = [(1:1:T)', myshadeU(1:1:T); (T:-1:1)', myshadeL(T:-1:1,1)];
% plot example.
figure
bar(x, 'red', 'facealpha', 0.2); hold on
patch(fill(:,1) , fill(:,2) , [0 0 1],'facealpha', 0.2); hold on

Réponse acceptée

Dave B
Dave B le 21 Oct 2021
First, you'll want the patch behind the bars, so call patch first.
You can keep the transparency on the patch, but if you don't want to blend with the bars then you'll need to make their faces fully opaque. If you want to keep the salmon-like color that you get from alpha here, you can instead 'desaturate' the color in the bar faces. I broke this out into a few lines so you can see how it works:
T= 30;
x=randn(T,1);
x(x<0)=0;
% get maximum of x as upper bound for shaded area.
mymax = max(x);
myshadeU = zeros(T,1);
myshadeU(1:15) = repmat(mymax, T/2, 1);
myshadeL = zeros(T,1);
% shaded area.
fill = [(1:1:T)', myshadeU(1:1:T); (T:-1:1)', myshadeL(T:-1:1,1)];
patch(fill(:,1) , fill(:,2) , [0 0 1],'facealpha', 0.2);
hold on
saturated_rgb = [1 0 0]; % fully saturated red
saturated_hsv=rgb2hsv(saturated_rgb); % Convert to hsv
unsaturated_hsv=saturated_hsv.*[1 .2 1]; % Reduce saturation
unsaturated_rgb=hsv2rgb(unsaturated_hsv); % Convert back to rgb
bar(x, 'FaceColor', unsaturated_rgb); hold on
  1 commentaire
David
David le 21 Oct 2021
thank you so much, this is exactly what i was looking for!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by