## how to label lines on a graph

on 1 Dec 2011

### Chad Greene (view profile)

on 10 Aug 2014

I have a program which asks for variable values of k. A function inputs these into an equation and displays a line on a graph for each value of k. How can i label each of these lines with the value of k used for each. The problem i am having is that the k values are variable and so are the amount of lines displayed on the graph, so i can't figure out how to do this for the values that are fed to the function. Any help would be much appreciated? Thanks, Scott

## Products

No products are associated with this question.

### Michael (view profile)

on 1 Dec 2011

The general method would be using the legend function, to which you give a vector of the plot object handles and a series of corresponding strings. For example,

```figure; hold on
a1 = plot(x,y1); M1 = "Curve 1";
a2 = plot(x,y2); M2 = "Curve 2";
legend([a1,a2], [M1, M2]);
```

The legend makes the connection between the plot object a1 and the string M1, and uses this to generate the legend. All you must do in your loop is devise a way to generate ai and Mi for a general integer i. I don't have MATLAB open now to test it but I think there must be a way using a combination of sprintf/num2str:

```sprintf('object%s',num2str(a));
```

Returns "object1" if a=1, "object2" if a=2, etc.,

Hope this helps, though not a complete answer. Mike

Robert Walker

### Robert Walker (view profile)

on 23 Jan 2014

Not to nitpick, but the commas in the legend function should be semicolons, looking like this:

```figure; hold on
a1 = plot(x,y1); M1 = "Curve 1";
a2 = plot(x,y2); M2 = "Curve 2";
legend([a1; a2], [M1; M2]);
```

### Matt Tearle (view profile)

Answer by Matt Tearle

### Matt Tearle (view profile)

on 1 Dec 2011

How about overlaying text on the graph, next to the lines?

```line(x,y)  % or plot(x,y) with a hold on
text(max(x),max(y),num2str(k))
```

You could play with the (x,y) location of the text. When you say "line" do you mean a straight line or, in general, a curve? The former would make calculating placement very easy; the latter would require some more cleverness, unless max or min works for you.

Harold

### Harold (view profile)

on 1 Dec 2011

the lines are curves, and i am not fussed about the location of the text, it just has to be somewhere.

Matt Tearle

### Matt Tearle (view profile)

on 1 Dec 2011

Great, then what I have should do the job... unless the curves all converge at the ends or something :)

### Chad Greene (view profile)

on 10 Aug 2014

label might do the trick.