Matplotlib Basics Tutorial
Introduction
Matplotlib is a widely used plotting library in Python, with over 50 million monthly downloads as of 2026. The current stable version is 3.11.1 (released July 2026). It provides a simple and effective way to create various types of visualizations, such as line plots, scatter plots, bar charts, histograms, and more. Whether you are a data scientist analyzing data trends, a researcher presenting experimental results, or a student visualizing mathematical functions, Matplotlib can be an invaluable tool.
Matplotlib offers two main interfaces for creating plots: the pyplot (state-based) interface and the object-oriented (OO) interface. This tutorial will start with the simpler pyplot approach and then introduce the OO interface, which is recommended for anything beyond quick, exploratory plots. We will cover the fundamental concepts, usage methods, common practices, and best practices of Matplotlib.
Table of Contents
- Installation
- Importing Matplotlib
- Basic Plotting
- Creating a Simple Line Plot
- Adding Labels and Titles
- The Object-Oriented Interface
- Customizing Plots
- Changing Line Styles and Colors
- Adjusting Axes
- Adding Legends
- Different Plot Types
- Scatter Plots
- Bar Charts
- Histograms
- Multiple Subplots
- Annotations
- Using Styles and Themes
- Saving Plots
- Best Practices
- Conclusion
- References
1. Installation
If you haven't installed Matplotlib yet, you can do so using pip, the Python package installer. Open your terminal or command prompt and run the following command:
pip install matplotlib
You can verify the installation by checking the version:
import matplotlib
print(matplotlib.__version__) # e.g., 3.11.1
2. Importing Matplotlib
In your Python script or notebook, you need to import Matplotlib. The most common way is to import the pyplot submodule with the alias plt. It is also standard practice to import NumPy, which Matplotlib uses extensively for numerical data:
import matplotlib.pyplot as plt
import numpy as np
Note: You may encounter older examples using
from pylab import *. This approach is deprecated and strongly discouraged because it pollutes the namespace and can lead to hard-to-track bugs. Always useimport matplotlib.pyplot as pltinstead.
3. Basic Plotting
Creating a Simple Line Plot
To create a basic line plot, you need to provide two lists: one for the x-values and one for the y-values.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()
In this example, the plt.plot() function takes the x and y values as arguments and creates a line plot. The plt.show() function displays the plot. In interactive environments like Jupyter notebooks, plots may display automatically without plt.show().
Adding Labels and Titles
You can make your plot more informative by adding labels to the axes and a title.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Simple Line Plot')
plt.show()
4. The Object-Oriented Interface
For more control over your plots — especially when working with multiple subplots or creating reusable code — Matplotlib's object-oriented (OO) interface is the recommended approach. Instead of relying on plt to track the "current" figure and axes implicitly, you explicitly create Figure and Axes objects:
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
ax.set_xlabel('X-axis label')
ax.set_ylabel('Y-axis label')
ax.set_title('Simple Plot')
plt.show()
The key difference is that you call methods directly on the ax object (e.g., ax.set_xlabel()) rather than on plt (e.g., plt.xlabel()). This makes it clear which plot you are modifying, which becomes essential when a figure contains multiple axes.
You can control the figure size using the figsize parameter, which takes a (width, height) tuple in inches:
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()
Both the pyplot and OO styles are valid, and Matplotlib's documentation uses both. As a general guideline, use the pyplot style for quick, interactive exploration and the OO style for scripts, functions, and complex figures.
5. Customizing Plots
Changing Line Styles and Colors
You can customize the appearance of the line in the plot. For example, you can change the line style to dashed and the color to red.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, linestyle='--', color='r')
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Customized Line Plot')
plt.show()
Common line styles include '-' (solid), '--' (dashed), ':' (dotted), and '-.' (dash-dot). Colors can be specified by name ('red', 'blue'), hex code ('#FF5733'), or RGB tuple ((0.2, 0.4, 0.6)).
You can also add markers to highlight individual data points:
plt.plot(x, y, linestyle='--', color='r', marker='o', markersize=8)
Adjusting Axes
You can also adjust the range of the axes. For instance, if you want to set the x-axis range from 0 to 6 and the y-axis range from 0 to 12:
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Adjusted Axes Plot')
plt.xlim(0, 6)
plt.ylim(0, 12)
plt.show()
In the OO interface, the equivalent is ax.set_xlim(0, 6) and ax.set_ylim(0, 12).
Adding Legends
When plotting multiple data series, a legend helps viewers distinguish between them. Add a label to each plot call and then call plt.legend():
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Trigonometric Functions')
plt.legend()
plt.show()
You can control the legend's position with the loc parameter (e.g., loc='upper right', loc='center'). For fine-grained placement, use bbox_to_anchor.
6. Different Plot Types
Scatter Plots
Scatter plots are useful for visualizing the relationship between two variables. To create a scatter plot, use the plt.scatter() function.
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.scatter(x, y)
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Scatter Plot')
plt.show()
Scatter plots support additional parameters like s (marker size), c (color), and cmap (colormap) for encoding extra dimensions of data:
np.random.seed(42)
x = np.random.randn(100)
y = np.random.randn(100)
colors = np.random.rand(100)
sizes = 100 * np.random.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.title('Scatter Plot with Color and Size')
plt.show()
Bar Charts
Bar charts are great for comparing categorical data. Here's an example of creating a bar chart:
labels = ['A', 'B', 'C', 'D']
values = [10, 25, 15, 30]
plt.bar(labels, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart')
plt.show()
For horizontal bar charts, use plt.barh():
plt.barh(labels, values)
plt.xlabel('Values')
plt.ylabel('Categories')
plt.title('Horizontal Bar Chart')
plt.show()
Histograms
Histograms are essential for understanding the distribution of a dataset:
data = np.random.randn(1000)
plt.hist(data, bins=30, edgecolor='black', alpha=0.7)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
7. Multiple Subplots
You can display multiple plots in a single figure using subplots. The plt.subplot() function is used for this purpose.
# Create a figure with 2 subplots
plt.subplot(2, 1, 1) # 2 rows, 1 column, 1st subplot
x1 = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
plt.plot(x1, y1)
plt.title('First Subplot')
plt.subplot(2, 1, 2) # 2 rows, 1 column, 2nd subplot
x2 = [1, 2, 3, 4, 5]
y2 = [1, 9, 5, 7, 3]
plt.plot(x2, y2)
plt.title('Second Subplot')
plt.tight_layout() # Adjust the layout
plt.show()
Using the OO interface with plt.subplots() is preferred for multi-subplot figures, as it gives you explicit control over each axes:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title('Plot 1')
ax2.plot([1, 2, 3], [1, 2, 3])
ax2.set_title('Plot 2')
fig.suptitle('Side-by-Side Subplots')
plt.tight_layout()
plt.show()
For more complex layouts, use plt.subplot_mosaic():
fig, axd = plt.subplot_mosaic([['left', 'right'],
['bottom', 'bottom']],
figsize=(8, 6))
axd['left'].set_title('Left')
axd['right'].set_title('Right')
axd['bottom'].set_title('Bottom (spans both columns)')
plt.tight_layout()
plt.show()
8. Annotations
Annotations let you highlight specific points on a plot with text and arrows:
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.annotate('Peak', xy=(np.pi / 2, 1), xytext=(np.pi / 2 + 0.5, 0.8),
arrowprops=dict(facecolor='black', shrink=0.05),
fontsize=12)
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.set_title('Annotated Sine Wave')
plt.show()
You can also add plain text to any location on the plot using ax.text():
ax.text(0.5, 0.5, 'Center of plot', transform=ax.transAxes,
ha='center', fontsize=14)
9. Using Styles and Themes
Matplotlib includes built-in style sheets that change the overall appearance of your plots. To view available styles:
print(plt.style.available)
To apply a style:
plt.style.use('ggplot')
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend()
plt.title('Plot with ggplot Style')
plt.show()
Popular styles include 'ggplot', 'fivethirtyeight', 'seaborn-v0_8', and 'dark_background'. You can also use a context manager to apply a style temporarily:
with plt.style.context('fivethirtyeight'):
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Temporary Style')
plt.show()
10. Saving Plots
You can save the generated plot as an image file. The plt.savefig() function is used for this. The format is inferred from the file extension (PNG, PDF, SVG, etc.).
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Saved Plot')
plt.savefig('saved_plot.png', dpi=150, bbox_inches='tight')
The dpi parameter controls resolution, and bbox_inches='tight' removes excess whitespace around the figure. When saving, call plt.savefig() before plt.show(), because plt.show() clears the figure in some backends.
11. Best Practices
- Use the OO interface for complex plots: When working with multiple subplots, reusable functions, or scripts, prefer
fig, ax = plt.subplots()over the pyplot state-based approach. It makes your code clearer and easier to maintain. - Keep it Simple: Avoid overcrowding your plots with too much information. Use clear labels and titles to convey the message effectively.
- Choose the Right Plot Type: Select the appropriate plot type based on the nature of your data. Use line plots for trends over time, bar charts for comparing categories, scatter plots for relationships between variables, and histograms for distributions.
- Use Consistent Styles: Maintain a consistent style throughout your plots, such as color schemes and line widths, for a professional look. Consider using
plt.style.use()or a custommatplotlibrcfile. - Add Legends When Plotting Multiple Series: Always include a legend when a plot contains more than one data series.
- Use
tight_layout(): Callplt.tight_layout()(or uselayout='constrained'inplt.subplots()) to automatically adjust spacing and prevent labels from overlapping. - Annotate Clearly: If you need to add additional information to the plot, use annotations in a clear and unobtrusive way.
- Save at High Resolution: Use
dpi=150or higher when saving plots for reports or publications.
12. Conclusion
Matplotlib is a powerful and flexible library for creating visualizations in Python. By understanding the basic concepts, the pyplot and object-oriented interfaces, different plot types, customization options, and best practices covered in this tutorial, you can effectively communicate data insights through visual means. Whether you are just starting out with data visualization or looking to enhance your existing skills, Matplotlib provides a solid foundation.
13. References
- Matplotlib official documentation — Comprehensive reference for all Matplotlib features
- Matplotlib Quick Start Guide — Official beginner tutorial covering both interfaces
- Python Plotting With Matplotlib (Guide) — In-depth walkthrough of Matplotlib's design and usage
- Matplotlib Styles Reference — Gallery of all available built-in styles
- Python Data Science Handbook by Jake VanderPlas — Free online book with a comprehensive Matplotlib chapter
Remember to practice and experiment with different examples to become more proficient in using Matplotlib for your specific needs.