How to label a line in Matplotlib (Python)?

To label a line in matplotlib, we can use the label parameter in the plot() method, then display the labels using legend().

Basic Line Labeling

Here's how to add labels to multiple lines and display them ?

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]

# Plot lines with labels
plt.plot(x, y1, label="Quadratic")
plt.plot(x, y2, label="Linear")

# Display the legend
plt.legend()
plt.show()

Customizing Legend Position

You can control where the legend appears using the loc parameter ?

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [5, 4, 3, 2, 1]
y2 = [1, 3, 2, 4, 5]

plt.plot(x, y1, label="Decreasing", color='red')
plt.plot(x, y2, label="Random", color='blue')

# Position legend at upper right
plt.legend(loc='upper right')
plt.title("Line Plot with Custom Legend Position")
plt.show()

Adding Line Styles and Markers

Enhance your labeled lines with different styles and markers ?

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
y3 = [5, 4, 3, 2, 1]

plt.plot(x, y1, label="Even numbers", linestyle='--', marker='o')
plt.plot(x, y2, label="Odd numbers", linestyle='-', marker='s')
plt.plot(x, y3, label="Countdown", linestyle=':', marker='^')

plt.legend(loc='center right')
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Multiple Lines with Different Styles")
plt.grid(True, alpha=0.3)
plt.show()

Legend Positioning Options

Location Description
'upper right' Top right corner (default)
'upper left' Top left corner
'center' Center of the plot
'best' Automatically chooses best location

Conclusion

Use the label parameter in plot() to name your lines, then call legend() to display them. Control legend placement with the loc parameter for better visualization.

Updated on: 2026-03-25T21:24:07+05:30

52K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements