Python Matplotlib pyplot – A Complete Guide

Last updated 1 month, 3 weeks ago | 157 views 75     5

pyplot is a module in the matplotlib library that provides a collection of functions resembling MATLAB’s plotting interface. It is designed for creating quick, simple, and interactive plots.

Whether you’re visualizing scientific data or plotting results for a machine learning model, pyplot is one of the most essential tools in a Python developer's toolbox.


What is matplotlib.pyplot?

matplotlib.pyplot is the state-based interface of Matplotlib. Each function in pyplot modifies the current figure or axes, and it provides a clean and intuitive syntax for building plots.

import matplotlib.pyplot as plt

Setting Up

To use pyplot, you first need to install Matplotlib if you haven’t already:

pip install matplotlib

In Jupyter Notebooks:

%matplotlib inline

Basic Structure of a pyplot Plot

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

plt.plot(x, y)
plt.title("Basic Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

Common pyplot Functions

Here are some of the most frequently used pyplot functions:

Function Purpose
plt.plot() Line plot
plt.scatter() Scatter plot
plt.bar() Vertical bar chart
plt.barh() Horizontal bar chart
plt.hist() Histogram
plt.pie() Pie chart
plt.xlabel() / plt.ylabel() Label axes
plt.title() Add plot title
plt.grid() Add grid lines
plt.legend() Add a legend
plt.savefig() Save the figure
plt.show() Display the figure

Plot Types and Examples

1. Line Plot

plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.title("Line Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

2. Scatter Plot

plt.scatter([1, 2, 3], [4, 5, 6])
plt.title("Scatter Example")
plt.show()

3. Bar Plot

x = ['A', 'B', 'C']
y = [5, 7, 3]
plt.bar(x, y)
plt.title("Bar Chart")
plt.show()

4. Histogram

data = [1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5]
plt.hist(data, bins=5)
plt.title("Histogram")
plt.show()

5. Pie Chart

labels = ['Python', 'Java', 'C++', 'JavaScript']
sizes = [35, 25, 25, 15]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart")
plt.show()

Customization Options

Line Styles and Markers

plt.plot([1, 2, 3], [4, 5, 6], color='green', linestyle='--', marker='o')

Add Grid

plt.grid(True)

Legends

plt.plot([1, 2, 3], [4, 5, 6], label='Growth')
plt.legend()

Figure Size

plt.figure(figsize=(8, 4))

Saving the Plot

plt.savefig('my_plot.png', dpi=300)

Using Multiple Plots (Subplots)

You can create multiple plots in one figure using plt.subplot():

plt.subplot(1, 2, 1)  # 1 row, 2 columns, first plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Plot 1")

plt.subplot(1, 2, 2)  # Second plot
plt.plot([1, 2, 3], [6, 5, 4])
plt.title("Plot 2")

plt.tight_layout()
plt.show()

✅ Complete Example

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]

# Create figure
plt.figure(figsize=(10, 5))

# Plot y1
plt.plot(x, y1, label='Series 1', color='blue', marker='o')

# Plot y2
plt.plot(x, y2, label='Series 2', color='red', linestyle='--')

# Customize
plt.title("Comparison of Two Series")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.legend()

# Save and show
plt.savefig("line_comparison.png", dpi=300)
plt.show()

Tips for Using pyplot

  • Use plt.figure() to explicitly define figure size and avoid overlapping issues.

  • Call plt.show() at the end of each plot to render correctly, especially outside notebooks.

  • Use plt.clf() or plt.close() to clear figures when running multiple plots in a script.

  • Use tight_layout() to prevent label and title overlaps.


⚠️ Common Pitfalls and How to Avoid Them

Pitfall Solution
Forgetting plt.show() Always call it to render the plot
Overlapping plots Use plt.figure() or plt.clf() before a new plot
Unreadable axes or titles Use plt.tight_layout()
Wrong order of function calls Save before plt.show(), not after
Too many elements in one plot Use plt.subplot() to separate visuals

Conclusion

The pyplot module of Matplotlib is a user-friendly interface that simplifies the process of creating all types of plots in Python. With just a few lines of code, you can create detailed and publication-ready visualizations.

By mastering pyplot, you gain the foundation needed to explore advanced plotting libraries like Seaborn, Plotly, or even Matplotlib’s object-oriented interface.