Search code examples
matlabmatlab-figuresurface

How to set surface transparency based on value in Matlab?


I am plotting a surface and I want to add transparancy based upon the value of z2. Namely, if z2 = max(z2), the transparency is 0 and when z2 = min(z2), the transparency is 1. How can I do this?

h=surf(x2,y2,z2);
set(h, 'EdgeColor','none', 'FaceColor','interp', 'FaceLighting','gouraud')

Solution

  • I actually just figured out how to do this for a little application I was developing. I will include a working example of the code which varies the transparency of a simple surface based upon the value of z at the points. The key part of the code is where you are specifying 'AlphaData', which allows you to dynamically change the transparency of the surface however you want.

    [x,y] = meshgrid([-2:.2:2]);
    z = x.*exp(-x.^2-y.^2);
    figure
    hold on
    colormap jet
    surf(x,y,z,'FaceAlpha','flat',...
    'AlphaDataMapping','none',...
    'AlphaData',abs(z),'Edgecolor','None')
    set(gcf,'position',[350,0,900,900])
    view([45,20])
    grid on
    colorbar ```