How to Use Pyplot in Matplotlib: Simple Guide with Examples
Use
matplotlib.pyplot by importing it as plt. Call plotting functions like plt.plot() to create graphs, then use plt.show() to display the plot.Syntax
The basic syntax to use pyplot involves importing it, creating plots with functions like plot(), and displaying them with show(). You can also add titles, labels, and legends.
import matplotlib.pyplot as plt: Imports pyplot with aliasplt.plt.plot(x, y): Plots y versus x as lines or markers.plt.title(),plt.xlabel(),plt.ylabel(): Add title and axis labels.plt.show(): Displays the plot window.
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [4, 5, 6] plt.plot(x, y) plt.title('Sample Plot') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A line plot window showing points (1,4), (2,5), (3,6) connected with a line, titled 'Sample Plot' with labeled axes.
Example
This example shows how to create a simple line plot with labels and display it using pyplot.
python
import matplotlib.pyplot as plt # Data x = [0, 1, 2, 3, 4] y = [0, 1, 4, 9, 16] # Create plot plt.plot(x, y, marker='o', linestyle='-', color='blue') plt.title('Square Numbers') plt.xlabel('Number') plt.ylabel('Square') # Show plot plt.show()
Output
A blue line plot with circular markers showing points (0,0), (1,1), (2,4), (3,9), (4,16) connected, titled 'Square Numbers' with labeled axes.
Common Pitfalls
Common mistakes when using pyplot include forgetting to call plt.show(), which means the plot won't display, or calling plt.plot() without data. Another pitfall is not clearing plots between multiple plots, causing overlap.
Always use plt.clf() or plt.close() to clear plots if making multiple figures in one script.
python
import matplotlib.pyplot as plt # Wrong: Missing plt.show() plt.plot([1, 2, 3], [4, 5, 6]) # Right: Add plt.show() to display plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Output
The first plot does not display; the second plot window appears showing the line plot.
Quick Reference
| Function | Purpose | Example |
|---|---|---|
| plt.plot() | Create line or scatter plot | plt.plot(x, y) |
| plt.title() | Set plot title | plt.title('My Plot') |
| plt.xlabel() | Set x-axis label | plt.xlabel('X axis') |
| plt.ylabel() | Set y-axis label | plt.ylabel('Y axis') |
| plt.show() | Display the plot | plt.show() |
| plt.clf() | Clear current figure | plt.clf() |
| plt.close() | Close plot window | plt.close() |
Key Takeaways
Import pyplot as plt to access plotting functions easily.
Use plt.plot() to create plots and plt.show() to display them.
Add titles and labels for clarity using plt.title(), plt.xlabel(), and plt.ylabel().
Remember to call plt.show() or your plot will not appear.
Clear plots with plt.clf() or plt.close() when making multiple figures.