JohnnyF
JohnnyF

Reputation: 1101

How to plot vertical line with string in MATLAB

I have two arrays, let it be called theArray1 theArray2 of N in this format:

5 13 20 ..
bloladsa adsad rwerds ..

and i want to add to my plot a vertical line at the {5,13,20,..} X values and that the string

in the same X value will be written let say on the lower part of the line (dont really care about the location)

I dont even have an idea how to do this so no code to show

edit the vertical lines i draw with :

hx = graph2d.constantline(theArray1, 'LineStyle',':', 'Color',[.7 .7 .7]);
changedependvar(hx,'x');

now i just need to add the text at those places

Upvotes: 0

Views: 1436

Answers (1)

kkuilla
kkuilla

Reputation: 2256

You could do this:

A={5, 'blablavla'; 13,'kikokiko';20,'bibobibo'}
lengthOfLine = 10;
for n=1:size(A,1)
    x = repmat(A{n,1},[1,lengthOfLine]);
    y = 1:lengthOfLine;
    plot(x,y)

    text(x(1)+0.1,y(1)+0.1,A{n,2})
    hold on
end    
hold off

% Adjust the axis so that the lines are more visible
axis([0 25 0 15])

enter image description here


Details

Loop through your items

for n=1:size(A,1)

Generate x and y values. The important thing is that x and y are of the same length. We use repmat to repeat a value e.g ten times.

x = repmat(A{n,1},[1,lengthOfLine]);
y = 1:lengthOfLine;

An example output would be

x = [   20   20   20   20   20   20   20   20   20   20];
y = [    1    2    3    4    5    6    7    8    9   10];

This will draw a vertical lines and x = 20.

Plot the x and y.

plot(x,y)

Add text to the plot. The coordinates of the text will refer to the coordinate system so I add 0.1 to the first x value x(1) so that the text will appear just to the right of the line.

text(x(1)+0.1,y(1)+0.1,A{n,2})
hold on

Adjust the axis so that the lines are more visible

axis([0 25 0 15])

Upvotes: 1

Related Questions