How to Create a Line Plot in Matplotlib: Simple Guide
To create a line plot in
matplotlib, use the plt.plot() function with your data points. Then call plt.show() to display the plot.Syntax
The basic syntax to create a line plot is:
plt.plot(x, y): Plots y versus x as lines and/or markers.x: List or array of x-axis values.y: List or array of y-axis values.plt.show(): Displays the plot window.
python
import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5] plt.plot(x, y) plt.show()
Example
This example shows how to plot a simple line graph of y = x squared for x values from 0 to 5.
python
import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [i**2 for i in x] plt.plot(x, y) plt.title('Line Plot of y = x^2') plt.xlabel('x') plt.ylabel('y') plt.show()
Output
A line plot window showing a curve starting at (0,0) and rising steeply to (5,25).
Common Pitfalls
Common mistakes when creating line plots include:
- Not calling
plt.show(), so the plot does not display. - Passing x and y lists of different lengths, causing errors.
- Forgetting to import
matplotlib.pyplotasplt.
python
import matplotlib.pyplot as plt # Wrong: Different lengths x = [1, 2, 3] y = [4, 5] # plt.plot(x, y) # This will cause an error # Right: x = [1, 2, 3] y = [4, 5, 6] plt.plot(x, y) plt.show()
Output
A line plot window showing a line connecting points (1,4), (2,5), and (3,6).
Quick Reference
Tips for creating line plots:
- Use
plt.plot(x, y, 'color_marker_style')to customize lines (e.g., 'ro-' for red circles with lines). - Add labels with
plt.xlabel()andplt.ylabel(). - Use
plt.title()to add a title. - Call
plt.grid(True)to add grid lines.
Key Takeaways
Use plt.plot(x, y) to create a line plot with your data points.
Always call plt.show() to display the plot window.
Ensure x and y have the same length to avoid errors.
Customize your plot with titles, labels, and colors for clarity.
Import matplotlib.pyplot as plt before plotting.