Search code examples
matlabmatlab-figure

How to shade area and make it transparent between two lines in MATLAB?


I shaded the area between two lines, it's not very clean:

area(xData,[Y1(:) ,Y2(:)-Y1(:)]); hold on

colormap([1 1 1; 0 0 1]);

How to make it transparent too in MATLAB? So that it comes like:

graph

ref:peltiertech.com


Solution

  • You can use the FaceAlpha property of the area object to set the transparency level:

    xData = 1:7;
    Y1 = [3 2 1 4 3 2 1];
    Y2 = [8 6 9 8 7 5 6];
    area(xData, Y2, 'EdgeColor',[0 .447 .741], 'FaceColor',[0.929 .694 .125], 'FaceAlpha',.3);
    hold on
    area(xData, Y1, 'EdgeColor',[0 .447 .741], 'FaceColor', [1 1 1]);
    

    A cleaner approach is to use patch instead of area:

    h = patch([xData xData(end:-1:1) xData(1)], [Y1 Y2(end:-1:1) Y1(1)], 'b');
    set(h, 'EdgeColor',[0 .447 .741], 'FaceColor',[0.929 .694 .125], 'FaceAlpha',.3)
    

    enter image description here