Search code examples
matlabplotannotationslinesurf

Unable to plot a line over a surf plot- the line is fragmented


I'm trying to plot a line over a surf plot in Matlab,but the line gets fragmented over some areas. I'm trying to create lines or squares to separate between different chunks of data. I tried doing this with annotation, There, the lines were not fragmented but it was too hard for me to position the rectangle at the exact spots.

If there is a solution using lines where they don't get fragmented, or a way to creating a rectangle where you just have to input starting X and ending X, that would be perfect.

mat=rand(4,125);
surf(mat');
meshgrid(-5:0.5:5);
view(2);
hold on
line([2 2],[1 140],'LineWidth',8,'Color',[1 0 0])

Solution

  • Both graphic objects, the surface and the line are plotted in the XY plane, hence you do see the line once its z value is higher than the z value of the surface plot and vice versa if the surface z is higher than the line z.

    You can plot the line in an raised plane, by adding an z-offset to avoid the problem:

    mat=rand(4,125);
    h = surf(mat');              % Save the handle of your surface object
    meshgrid(-5:0.5:5);
    view(2);
    hold on
    z_max = max(max(get(h,'ZData')));   % get max z value of surface plot
    
    % Now plot your line in an z_plane above the highest surf point
    line([2 2], [1 140], z_max*ones(1,2)+1, 'LineWidth', 8, 'Color', [1 0 0])
    

    Now the line is always on top of the surface plot

    enter image description here