Hello everybody
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.

1 Kommentar

Jan
Jan am 27 Sep. 2017
From the bottom of the figure to the top, or from the axes?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Star Strider
Star Strider am 27 Sep. 2017

2 Stimmen

To draw the lines, you need to specify duplicate x-coordinates to match the two-element ylim vectors. Here, the ylim matrix is transposed (the ' operator) so the vertical lines plot correctly.
The text call to label the lines is straightforward. You need to provide a vector of x and y coordinates, and a matching cell array of strings.
Try this:
x = 0:pi/100:2*pi;
y = sin(x);
figure(1)
plot(x,y)
hold on
plot([1 3 5; 1 3 5], [ylim; ylim; ylim]')
hold off
text([1 3 5], 0.7*[1 1 1], {'Test 1', 'Test 2', 'Test 3'})
It’s not ‘tricky’ really. It just requires a bit of experience with the functions, and when necessary, experimentation to see what works.

3 Kommentare

Sepp
Sepp am 28 Sep. 2017
Bearbeitet: Sepp am 28 Sep. 2017
Thanks for your answer. For the text you have used 0.7*[1 1 1] where 1 is the upper bound of the figure. Unfortunately, the upper bound in my figure is flexible and ylim instead of 1 does not work (I'm getting an error). Is there a possibility to make it flexible?
yl = ylim() ;
text([1 3 5], yl(2)*0.7*[1 1 1], {'Test 1', 'Test 2', 'Test 3'})
Star Strider
Star Strider am 28 Sep. 2017
@Cedric — Thank you! (I was off doing other things for a few minutes.)
@Sepp — My pleasure. The key is to use ylim to scale the y-position of the labels. The advantage is that with ylim (in Cedric’s comment, yl(2) is the upper limit of the y-axis) automatically rescales with changing limits of the y-axis.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 27 Sep. 2017

2 Stimmen

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y);
hold('on');
line([1 3 5; 1 3 5], [-10, -10, -10; 10, 10, 10], 'YLimInclude', 'off');
text([1 3 5], [1, 1, 1], {'Test 1', 'Test 2', 'Test 3'}, ...
'VerticalAlignment', 'top')
Disabling 'YLimInclude' let the Y-limits untouched by this object. Then you can even Zoom in the diagram without seeing the end of the line (at least until a certain level). Unfortunately YLimInclude is undocumented, but it works for many years now.

Kategorien

Mehr zu Line Plots finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 27 Sep. 2017

Kommentiert:

am 17 Okt. 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by