Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to name different lines in the same plot of Matplotlib?
To name different lines in the same plot of matplotlib, we can use the label parameter in the plot() method and display them with legend(). This helps distinguish between multiple data series on the same plot.
Steps to Name Different Lines
Set the figure size and adjust the padding between and around the subplots.
Create data points for different lines.
Plot each line using
plot()method with uniquelabelparameter.Add a legend to display the line names using
legend().Display the figure using
show()method.
Example
Here's how to plot multiple lines with different names ?
import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True points1 = [2, 4, 1, 5, 1] points2 = [3, 2, 0, 4, 3] plt.plot(points1, 'g--', label="Line A") plt.plot(points2, 'r-o', label="Line B") plt.legend() plt.show()
The output shows two distinct lines with their respective names in the legend ?
Customizing Legend Position
You can control the legend position using the loc parameter ?
import matplotlib.pyplot as plt
data1 = [1, 3, 2, 4, 2]
data2 = [2, 1, 3, 2, 4]
plt.plot(data1, 'b-', label="Dataset 1", linewidth=2)
plt.plot(data2, 'm--', label="Dataset 2", linewidth=2)
plt.legend(loc='upper right')
plt.title('Multiple Lines with Custom Legend')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Common Legend Positions
| Location | Description |
|---|---|
'upper right' |
Top right corner (default) |
'upper left' |
Top left corner |
'lower right' |
Bottom right corner |
'best' |
Automatically chooses best position |
Conclusion
Use the label parameter in plot() and call legend() to name different lines in matplotlib. This creates clear, readable plots with properly identified data series.
