← Back to Python Course | Chapter 13: Data Science & Web | Lesson 5 of 14

Python Matplotlib Basics

What is Matplotlib?

Matplotlib is Python's foundational 2D plotting library, and its pyplot module offers a MATLAB-inspired interface for building charts step by step. This tutorial's examples use the non-interactive Agg backend, which renders directly to image files rather than opening a graphical window, so the code runs safely without a display attached.

Example: What is Matplotlib?

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig("chart.png")
print("Chart saved")

Customizing Labels and Titles

plt.title(), plt.xlabel(), and plt.ylabel() add descriptive text around a plot, and plt.legend() adds a key identifying each line or series when a chart shows more than one. A chart without these is often unreadable to anyone besides the person who made it, since the axes and series carry no context on their own.

Example: Customizing Labels and Titles

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], label="Sales")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Amount")
plt.legend()
plt.savefig("chart.png")

Line Customization

The color, linewidth, and linestyle arguments to plt.plot() control a line's visual appearance -- letting you distinguish multiple series on the same chart by more than just their shape, which matters especially once a plot has three or more overlapping lines.

Example: Line Customization

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], color="red", linewidth=2, linestyle="--")
plt.savefig("chart.png")
print("Styled line saved")

Creating Gridlines

plt.grid(True) overlays light reference lines across the plotting area, making it much easier for a viewer to read off approximate values at a glance rather than having to visually interpolate between bare axis tick marks.

Example: Creating Gridlines

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
plt.grid(True)
plt.savefig("chart.png")

Saving Figures

plt.savefig('filename.png') writes the current figure to disk as an image file, supporting formats like PNG, PDF, and SVG based on the file extension you give it. This is how generated charts get embedded into reports, dashboards, or web pages instead of only appearing in an interactive window.

Example: Saving Figures

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.plot([1, 2, 3])
plt.savefig("chart.png")
print("Saved as PNG")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.