Python:Matplotlib pyplot
The pyplot is a state-based interface module in the matplotlib library that provides a MATLAB-like way of plotting in Python. It serves as the primary entry point for creating plots and visualizations by offering a collection of functions that make changes to a figure, such as creating a figure, creating a plotting area in a figure, plotting lines, decorating the plot with labels, and more. The module maintains an internal state that tracks the current figure and axes, allowing users to build plots incrementally without explicitly managing figure objects.
pyplot is widely used in data science, scientific computing, academic research, and business analytics for creating static, animated, and interactive visualizations. It’s particularly popular for exploratory data analysis, creating publication-quality plots, generating reports with embedded charts, and building dashboards. The module’s simple syntax makes it ideal for quick plotting tasks, prototyping visualizations, and educational purposes where users need to create plots with minimal code.
Syntax
pyplot does not have a single syntax since it’s a collection of plotting functions. Instead, here are the essential steps to create plots using pyplot:
- Import the module:
import matplotlib.pyplot as plt - Prepare data: Create or load the data to be plotted
- Create plot: Use plotting functions like
plt.plot(),plt.scatter(),plt.bar(), etc. - Customize plot: Add labels, titles, legends using functions like
plt.xlabel(),plt.title(),plt.legend() - Display plot: Use
plt.show()to display the plot orplt.savefig()to save it
Common pyplot functions include:
plt.plot(): Creates line plots and scatter plotsplt.bar(): Creates bar chartsplt.hist(): Creates histogramsplt.scatter(): Creates scatter plotsplt.xlabel(): Sets x-axis labelplt.ylabel(): Sets y-axis labelplt.title(): Sets plot titleplt.legend(): Adds legend to the plotplt.show(): Displays the plotplt.savefig(): Saves the plot to a file
pyplot functions typically modify the current figure and axes, and most functions return the created objects for further customization.
Example 1: Basic Line Plot using pyplot
This example demonstrates the fundamental usage of pyplot to create a simple line plot, which is the most common starting point for data visualization:
import matplotlib.pyplot as pltimport numpy as np# Create sample datax = np.array([1, 2, 3, 4, 5]) # X-axis valuesy = np.array([2, 4, 6, 8, 10]) # Y-axis values# Create a line plotplt.plot(x, y)# Add labels and titleplt.xlabel('X Values')plt.ylabel('Y Values')plt.title('Basic Line Plot')# Display the plotplt.show()
The output of this code will be:

This example creates a simple line plot connecting five points. The plt.plot() function takes the x and y coordinates and draws a line connecting them. The plt.xlabel(), plt.ylabel(), and plt.title() functions add descriptive labels to make the plot more informative and professional-looking.
Example 2: Sales Data Visualization
This example shows how pyplot can be used to visualize real-world business data, specifically monthly sales figures for analysis and reporting.
import matplotlib.pyplot as pltimport numpy as np# Monthly sales data for a retail storemonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']sales = [15000, 18000, 22000, 19000, 25000, 28000] # Sales in dollars# Create a bar chart for better categorical data representationplt.bar(months, sales, color='skyblue', edgecolor='navy')# Customize the plot for professional presentationplt.xlabel('Month')plt.ylabel('Sales ($)')plt.title('Monthly Sales Performance - Q1 & Q2 2024')# Add value labels on top of each barfor i, v in enumerate(sales):plt.text(i, v + 500, f'${v:,}', ha='center', fontweight='bold')# Rotate x-axis labels for better readabilityplt.xticks(rotation=45)# Add grid for easier value readingplt.grid(axis='y', alpha=0.3)# Adjust layout to prevent label cutoffplt.tight_layout()# Display the plotplt.show()
The output of this code will be:

This example demonstrates the practical business use of pyplot for sales analysis. It creates a professional-looking bar chart with customized colors, value labels, grid lines, and proper formatting. The plt.tight_layout() function ensures all elements fit properly within the figure boundaries.
Frequently Asked Questions
1. What is the difference between pyplot and matplotlib?
The matplotlib is the entire plotting library, while pyplot is a specific module within matplotlib that provides a MATLAB-like interface. pyplot is the most commonly used part of matplotlib for creating quick plots and interactive visualizations.
2. Do I need to call plt.show() every time?
Yes, plt.show() is required to display plots in most environments. However, in Jupyter notebooks, plots may display automatically, and when saving plots with plt.savefig(), you don’t need plt.show() unless you also want to display the plot.
3. Can I create multiple plots in one script?
Yes, you can create multiple separate plots by calling plt.figure() before each new plot, or create subplots within a single figure using plt.subplot() or plt.subplots().
4. How do I save plots instead of displaying them?
Use plt.savefig('filename.png') before plt.show(). You can save in various formats, including PNG, PDF, SVG, and JPEG, by changing the file extension.
5. Is pyplot suitable for complex, multi-panel figures?
While pyplot can handle complex figures, the object-oriented matplotlib API is recommended for complex, multi-panel figures as it provides more control and is easier to manage programmatically.
pyplot
- .axis()
- Gets or sets the properties of the plot axes, including axis limits, scaling, and visibility.
- .bar()
- Returns a chart/graph that represents categorical data with vertical bars.
- .boxplot()
- Creates box-and-whisker plots to display statistical summaries of datasets.
- .figure()
- Creates a new figure window or activates an existing one for plotting.
- .fill()
- Fills the area enclosed by specified x and y coordinates to create a filled polygon on the plot.
- .hist()
- Creates histograms to visualize data distributions in Python.
- .legend()
- Creates and customizes legends to identify plot elements in matplotlib visualizations.
- .pie()
- Creates a pie chart based on a given array of values.
- .plot()
- Creates line and marker plots to visualize relationships between variables in Matplotlib.
- .scatter()
- Creates scatter plots to visualize relationships between variables.
- .stackplot()
- Creates a stacked area plot to show how multiple datasets contribute cumulatively over time or categories.
- .subplot()
- Creates a subplot within the same figure.
- .subplots()
- Creates a figure and a grid of subplots with a single function call.
- .xlim()
- Gets or sets the x-axis limits of the current axes in a Matplotlib plot.
- step()
- Draws step plots where y-values change at discrete x-positions.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Matplotlib on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours