Plot Multiple Lines in Matplotlib
Matplotlib is a powerful Python library used for data visualization. It is a fantastic tool for creating a wide range of interactive, highly customizable plots and graphs. It can also be used to plot multiple lines on the same graph. This capability allows comparison of data across different categories, as well as the ability to view trends over time. It is important to note that matplotlib requires the data to be in a specific format before it can be plotted. To ensure that the data is in the right format, it is recommended to use NumPy arrays. This tutorial will demonstrate how to use matplotlib to plot multiple lines on the same graph.
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
.png)
Hosted By
Ryan Valles
Founder, Interview Kickstart

Our tried & tested strategy for cracking interviews

How FAANG hiring process works

The 4 areas you must prepare for

How you can accelerate your learnings
Register for Webinar
The following code creates a simple line graph with multiple lines in Matplotlib:
```python
import matplotlib.pyplot as plt
# Create two data sets
x1 = [1, 2, 3, 4]
y1 = [2, 4, 6, 8]
x2 = [1, 2, 3, 4]
y2 = [3, 6, 9, 12]
# Plot the data
plt.plot(x1, y1, label="Line 1")
plt.plot(x2, y2, label="Line 2")
# Add labels, title, and legend
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Multiple Line Graph')
plt.legend()
# Show the graph
plt.show()
```
This code uses the `matplotlib.pyplot` library to create a line graph with two sets of data. First, two data sets (`x1` and `y1`, `x2` and `y2`) are created. Next, the `plot()` function is used to plot the data in the graph. Labels, title, and legend are added to the graph with the `xlabel()`, `ylabel()`, `title()`, and `legend()` functions. Finally, the `show()` function is used to show the graph.