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.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
CroCo
  • 5,531
  • 9
  • 56
  • 88

2 Answers2

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.

Community
  • 1
  • 1
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
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

Benoit_11
  • 13,905
  • 2
  • 24
  • 35
  • this doesn't automatically fill the x axis values. In my case, I have only y values. This function throws out an error. – CroCo Aug 17 '15 at 21:39
  • 1
    @CroCo `x` is just `x = 1:numel(y)`, isn't it? – Robert Seifert Aug 17 '15 at 22:00
  • 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. – CroCo Aug 17 '15 at 22:10
  • can you post the whole code that reproduces the error as an edit to your question? – Benoit_11 Aug 18 '15 at 10:41
  • @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? – CroCo Aug 19 '15 at 15:25