Search code examples
matlabcolorssurf

Filling an area above a curve with many colors (matlab, surf)


I'm trying to create a figure in matlab that looks like this: desired figure

I am doing so by: (i) assigning value points to each x,y coordinate, (ii) plotting a surf, and (iii) change the view point so the third axis is not seen. Here is the code:

    x = linspace(0, 1, 10);
    y = linspace(0, 1, 10);
    z = linspace(0, 1, 10);
    z = repmat(z, 10, 1);
    z = flipud(triu(z));
    z(z==0) = nan;

    hold off
    surf(x, y, z, 'linestyle', 'none')
    colormap([linspace(0.39, 1, 20)',linspace(0.58, 0.25, 20)', linspace(0.93, 0.25, 20)']);
    colorbar
    xlim([x(1) x(end)])
    shading interp
    view([90 -90])
    hold on
    plot(x, 1-y, 'linewidth', 2)

I get the following figure: matlab figure I get

As you can see, there a lot of white spaces above the line which I would like to be in color as well. Unfortunately, I cannot add any more grid points as calculating the actual value of the points takes a lot of time (unlike the example above).

Is there a way to have matlab draw colors in those white spaces as well?

Thanks!


Solution

  • You can try to use patch function to create filled polygon.
    See http://www.mathworks.com/help/matlab/ref/patch.html

    Try the following code:

    vert = [0 1;1 1;1 0]; % x and y vertex coordinates
    fac = [1 2 3]; % vertices to connect to make triangle
    fvc = [1 0 0; 1 1 1; 0 0 1];
    patch('Faces',fac,'Vertices',vert,'FaceVertexCData',fvc,'FaceColor','interp');
    

    Result is close:
    enter image description here


    I was managed to get closer to the desired figure:

    close all
    
    x = linspace(0, 1, 10);
    y = linspace(0, 1, 10);
    
    %colorbar
    xlim([x(1) x(end)])
    
    %Fill rectangle.
    vert = [0 0; 1 0; 1 1; 0 1]; % x and y vertex coordinates
    fac = [1 2 3 4]; % vertices to connect to make squares
    %patch('Faces',fac,'Vertices',vert,'FaceColor','red')
    fvc = [1 0 0; 0.6 0.7 1; 0.6 0.7 1; 1 0 0]; %Color of vertices (selected to be close to example image).
    patch('Faces',fac,'Vertices',vert,'FaceVertexCData',fvc,'FaceColor','interp')
    hold on
    
    %Fill lower triangle with white color.
    vert = [0 0;0 1;1 0]; % x and y vertex coordinates
    fac = [1 2 3]; % vertices to connect to make triangle
    fvc = [1 1 1; 1, 1, 1; 1, 1, 1]; %White color
    patch('Faces',fac,'Vertices',vert,'FaceVertexCData',fvc,'FaceColor','interp');
    
    plot(x, 1-y, 'linewidth', 2)
    
    set(gca,'Xtick',[],'Ytick',[]); %Remove tick marks
    

    Result:
    enter image description here