How to set the opacity for a plot?
Asked Answered
W

2

9

I have some data to be plotted in one figure. Noise data is ruining other data. How can I change the transparency level of a given data? In my case, I'm using hold all command for plotting several data. One of the solution is to change the LineWidth but I couldn't find a way for transparency option. I've tried alpha as follows

plot( noise_x, 'k', 'LineWidth', 1, 'alpha', 0.2)

but with no luck.

Watercourse answered 17/8, 2015 at 18:10 Comment(0)
O
18

With the introduction of the new graphic engine HG2 in Matlab R2014b, things got pretty easy. One just needs to dig a little.

The color property now contains a forth value for opacity/transparency/face-alpha, so that's all you need to change:

x = linspace(-10,10,100); y = x.^2;
p1 = plot(x,y,'LineWidth',5); hold on
p2 = plot(x,-y+y(1),'LineWidth',5);

% // forth value sets opacity
p1.Color(4) = 0.5;
p2.Color(4) = 0.5;

enter image description here

Even color gradients are nothing special anymore.

Outleap answered 17/8, 2015 at 21:5 Comment(5)
I have Matlab R2014a.Watercourse
@Watercourse That's a bummer. Then you need to go for Benoits answer or, if you don't want to use external functions, follow my link to Hoki's answer.Outleap
Nice one I did not know about that 4th color property thanks!Azeria
@thewaywewalk It is a fantastic answer!! could you also add some notes on the other 3 colour properties?Spradling
You mean Color(1:3)? These are just the normalized rgb values matlab uses.Outleap
A
2

You can use the patchline submission from the File Exchange, in which you can manipulate line objects as if they were patch objects; i.e. assign them transparency (alpha) values.

Here is some sample code using the function:

clc;clear;close all

n = 10;
x = 1:n;

y1 = rand(1,n);
y2 = rand(1,n);
y3 = rand(1,n);

Y = [y1;y2;y3];

linestyles = {'-';'-';'--'};
colors = {'r';'k';'b'};
alphavalues = [.2 .5 .8];

hold on
for k = 1:3
    patchline(x,Y(k,:),'linestyle',linestyles{k},'edgecolor',colors{k},'linewidth',4,'edgealpha',alphavalues(k))
end

and output:

enter image description here

Azeria answered 17/8, 2015 at 20:50 Comment(5)
this doesn't automatically fill the x axis values. In my case, I have only y values. This function throws out an error.Watercourse
@Watercourse x is just x = 1:numel(y), isn't it?Outleap
This code similar to my case x = 0:0.01:pi; patchline(sin(x)). This throws out an error Index exceeds matrix dimensions. If I use plot(sin(x)), there is no error.Watercourse
can you post the whole code that reproduces the error as an edit to your question?Azeria
@Benoit_11, I've posted it in my comment above yours. Basically, plot does the job without explicitly providing the x-axis values. This is not the case with patchline. Is there a way to overcome this problem?Watercourse

© 2022 - 2024 — McMap. All rights reserved.