Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

how to label lines on a graph

Asked by Harold on 1 Dec 2011
Latest activity Answered by Chad Greene on 10 Aug 2014 at 18:46

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

0 Comments

Harold

Products

No products are associated with this question.

3 Answers

Answer by Michael 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

1 Comment

Robert Walker 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]);
Michael
Answer by Matt Tearle 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.

2 Comments

Harold 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 on 1 Dec 2011

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

Matt Tearle
Answer by Chad Greene on 10 Aug 2014 at 18:46

label might do the trick.

0 Comments

Chad Greene

Contact us