Learn Python Programming  /  Data Visualization  /  Matplotlib Basics

Matplotlib Basics

Matplotlib is Python's foundational plotting library — most other visualization tools, including pandas plotting and Seaborn, are built directly on top of it.

Installing and Importing

R Code
pip install matplotlib

import matplotlib.pyplot as plt

A Basic Line Plot

R Code
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 6]

plt.plot(x, y)
plt.title("My First Plot")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()

The Figure and Axes Structure

Matplotlib has two ways to build a plot: the quick plt.plot() style shown above, and the more explicit figure/axes style, which gives more control and is recommended once your charts get more complex.

R Code
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, y, marker="o", color="steelblue")
ax.set_title("Figure/Axes Style")
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()
💡 Tip
Stick with plt.plot() for a single, quick chart. Switch to fig, ax = plt.subplots() as soon as you need multiple subplots in one figure, or want to build reusable plotting functions.

Multiple Plots in a Grid

R Code
fig, axes = plt.subplots(1, 2, figsize=(10, 4))

axes[0].plot(x, y)
axes[0].set_title("Plot A")

axes[1].scatter(x, y)
axes[1].set_title("Plot B")

plt.tight_layout()
plt.show()

Advanced: Saving a Figure to a File

🚀 Advanced Example
savefig() writes the figure to disk at publication quality - essential for including charts in a report or paper.
R Code
fig, ax = plt.subplots()
ax.plot(x, y)
plt.savefig("my_chart.png", dpi=300, bbox_inches="tight")

Key Points

  • matplotlib.pyplot (usually imported as plt) is the foundation of Python data visualization.
  • plt.plot() is quick and simple; fig, ax = plt.subplots() gives more control and supports multiple subplots.
  • plt.savefig("name.png", dpi=300) exports a chart at publication quality.