iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Matplotlib Tutorial

matplotlib is Python's foundational charting library. Most other plot tools (seaborn, plotnine, pandas .plot()) wrap it.

Install

SHELL
pip install matplotlib

Your first chart

PYTHON
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

plt.plot(x, y)
plt.title('y = x²')
plt.xlabel('x'); plt.ylabel('y')
plt.show()

Common chart types

FunctionDraws
plt.plotLine.
plt.scatterScatter plot.
plt.bar / plt.barhBars.
plt.histHistogram.
plt.piePie chart.
plt.imshowImage / heatmap.

Subplots

PYTHON
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot(x, y)
axes[1].bar(['a', 'b', 'c'], [3, 1, 4])
fig.suptitle('Two charts side by side')
plt.show()

Save to a file

PYTHON
plt.savefig('chart.png', dpi=150, bbox_inches='tight')

The pyplot vs OO style

  • pyplot — quick and stateful: plt.plot, plt.title, plt.show. Like MATLAB.
  • Object-oriented — explicit Figure / Axes references: ax.plot, ax.set_title. Better for complex charts and reusable code.
Tip: For statistical plots, seaborn (built on matplotlib) is much higher level. For interactive dashboards, plotly outputs HTML/JS.

Example

Example
# import matplotlib.pyplot as plt
# plt.plot([1, 2, 3], [1, 4, 9])
# plt.show()
print('matplotlib draws charts.')
Try it Yourself »

Exercise

Display the figure.

plt. ()

Test yourself

Q1. Show the figure with…
Q2. For higher level statistical plots use…
Q3. Save to disk with…

Discussion

Loading…