Search code examples
matlabmatlab-figure

Vertical lines with text in Matlab plot


I have created a plot in Matlab. Let's assume for simplicity that I have the following plot:

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

Now I would like to add vertical lines (going from the bottom of the figure to the top) at positions x = 1, x = 3 and x = 5. Additionally, the vertical lines should have text (next to the line or on top of the line). For example, for the line at x = 1 I would like to have the text "test 1".

How can this be done? This seems to be a pretty tricky thing in Matlab.


Solution

  • Here are some ways to draw lines:

    x = 0:pi/100:2*pi;
    y = sin(x);
    plot(x,y,[1 1],[-1 1],[3 3],[-1 1],[5 5],[-1 1]);
    

    x = 0:pi/100:2*pi;
    y = sin(x);
    plot(x,y); hold on;
    for ind1 = 1:2:5
      line([ind1 ind1],[min(y) max(y)],'Color',[0 0 0]);
    end
    

    x = 0:pi/100:2*pi;
    y = sin(x);
    A = zeros(6); A(sub2ind(size(A),1:6,[2 1 4 3 6 5])) = 1;
    plot(x,y); hold on; gplot(A, [repelem(1:2:5,1,2).', reshape(repelem([1 -1],3,1).',[],1)]);
    

    Etc.

    Either use hold on and plot in several commands, or provide all inputs to your plot function right aways to get the desired result. Consult the documentation of the above functions for more information.

    For texts refer to text.