Plotting with plt.plot()
The plt.plot() function is one of the most fundamental and versatile tools in Matplotlib.
It creates line plots by connecting data points along the x- and y-axes.
If you only pass one list of values, Matplotlib assumes they represent the y-values and automatically generates x-values starting from 0.
Plotting X and Y Values
When both x and y values are provided, Matplotlib connects each pair of points with a line by default.
Plotting X and Y Values
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y)
plt.title("Sample Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
- The order of
xandymatters. Both lists must be the same length. - If the plot looks wrong, check that your data is properly aligned.
Plotting Only Y Values
You can also plot a list of values without specifying x.
In that case, the x-axis will automatically be set to [0, 1, 2, ...].
Plotting Only Y Values
y = [5, 9, 4, 7]
plt.plot(y)
plt.title("Auto X-Axis")
plt.ylabel("Y Values")
plt.show()
This method is great for quick visual checks of any one-dimensional data, especially during early exploration.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.