Matplotlib Basics
Python · Data Visualization
Theory
Matplotlib is Python's foundational plotting library; pandas' df.plot() and seaborn both draw with it underneath. Every chart is built from two main objects. The Figure is the whole canvas, and an Axes is one plotting area inside it with its own x-axis, y-axis, title and data. Everything you see, such as lines, bars and text, is an artist drawn on an Axes.
The recommended object-oriented style makes these explicit: fig, ax = plt.subplots() creates a Figure with one Axes, then ax.plot(x, y) draws, ax.set_title() and ax.set_xlabel() add text, and fig.savefig('sales.png') writes an image. The quicker pyplot style (plt.plot, plt.title) acts on the current Axes behind the scenes, which is handy for one-off charts but confusing once you have several. plt.show() displays the figure in a script; notebooks usually display it automatically.
Why we use it
A chart shows patterns, trends and outliers that a table of numbers hides. Understanding the Figure and Axes model lets you control every part of a chart and build multi-panel figures instead of fighting the defaults.
When to use it
Use matplotlib when you need full control, multi-panel layouts or report-ready images. For quick charts straight from a DataFrame use df.plot(); for statistical charts with less code use seaborn; for interactive web charts consider a library such as Plotly.
How it works
- import matplotlib.pyplot as plt
- fig, ax = plt.subplots() creates the canvas and one Axes
- Draw data: ax.plot / ax.bar / ax.scatter
- Add title, axis labels and legend
- Saving for a report? Yes: fig.savefig('chart.png', dpi=150). No: plt.show() to display.
- Chart rendered
Syntax
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y)
ax.set_title('...') ax.set_xlabel('...') ax.set_ylabel('...')
plt.show()Example
fig, ax = plt.subplots()
ax.plot(['Jan', 'Feb', 'Mar'], [100, 250, 300])
ax.set_title('Monthly sales')
plt.show()Key points
- A Figure is the canvas; an Axes is one chart inside it
- fig, ax = plt.subplots() is the recommended starting point
- Use ax.set_title / ax.set_xlabel in OO style, plt.title in pyplot style
- plt.show() displays; fig.savefig() writes a file
- Close figures you no longer need with plt.close(fig)