How to Label Lines in MATLAB

Ammar Ali Feb 02, 2024
How to Label Lines in MATLAB

This tutorial will discuss how to label lines in the plot using the text() function in MATLAB.

Add Label to Lines Using the text() Function in MATLAB

You can use the text() function to add labels to the lines present in the plot. You need to pass the x and y coordinate on which you want to place the label. Simply plot the variable, select the coordinates from the plot, and then use the text() function to place the label on the selected coordinates. If you give the coordinates which don’t lie on the plot, you can’t see the label. We can also change the properties of the text like the font size using the FontSize property and the color using the Color property etc. For example, let’s plot a cosine wave and label it with font size 16 and blue color. See the code below.

t = 1:0.01:2;
plot(cos(2*pi*t))
t = text(90,0.8,'\leftarrowCosine','FontSize',16,'Color','b')

Output:

Add Label to Lines using text() function in matlab

You can give your desired color to the label by defining it after the label using the Color property. You can also add multiple labels at multiple positions on the plot with different names, line styles, colors, and sizes. For example, let’s add one more plot and label on the above graph with sine name of green color, a right arrow, and 16 font size. See the code below.

t = 1:0.01:2;
plot(cos(2*pi*t))
t1 = text(90,0.8,'\leftarrowCosine','FontSize',16,'Color','b')
hold on
plot(sin(2*pi*t),'Color','g')
t2 = text(22,0.6,'Sine\rightarrow','FontSize',16,'Color','g')

Output:

Multiple Labels using text() function in matlab

Check this link for more information about the text() function.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - MATLAB Plot