You are on page 1of 1

Matplotlib for beginners

Matplotlib is a library for making 2D plots in Python. It is


Z = np.random.uniform(0, 1, (8,8)) 765 Organize
designed with the philosophy that you should be able to
create simple plots with just a few commands: 432 You can plot several data on the the same figure, but you
ax.contourf(Z)
1 can also split a figure in several subplots (named Axes):
1 Initialize
Z = np.random.uniform(0, 1, 4) 765 1234567 765
432
X = np.linspace(0, 10, 100)
import numpy as np Y1, Y2 = np.sin(X), np.cos(X) 432
import matplotlib.pyplot as plt ax.pie(Z)
1 ax.plot(X, Y1, X, Y2)
1
Z = np.random.normal(0, 1, 100) 71
61
51 1234567 1234567
2 Prepare
41
31
21
fig, (ax1, ax2) = plt.subplots(2,1)
ax1.plot(X, Y1, color=”C1”)
X = np.linspace(0, 4*np.pi, 1000) ax.hist(Z)
111 ax2.plot(X, Y2, color=”C0”)
Y = np.sin(X)
X = np.arange(5) 765 1234567
432
fig, (ax1, ax2) = plt.subplots(1,2)
3 Render Y = np.random.uniform(0, 1, 5) ax1.plot(Y1, X, color=”C1”)

fig, ax = plt.subplots()
ax.errorbar(X, Y, Y∕4)
1 ax2.plot(Y2, X, color=”C0”)

ax.plot(X, Y) Z = np.random.normal(0, 1, (100,3)) 765 1234567


fig.show()
432 Label (everything)
ax.boxplot(Z)
1
4 Observe
246 ax.plot(X, Y)
543
A Sine wave

21
1.0 fig.suptitle(None)
0.5 Tweak ax.set_title(”A Sine wave”)

1234567
0.0
0.5 You can modify pretty much anything in a plot, including lim-
ax.plot(X, Y)
1.0 its, colors, markers, line width and styles, ticks and ticks la-
0 5 10 15 20 25 30 ax.set_ylabel(None)
bels, titles, etc.
ax.set_xlabel(”Time”)

765
Time
Choose X = np.linspace(0, 10, 100)
Y = np.sin(X) 432 Explore
Matplotlib offers several kind of plots (see Gallery): ax.plot(X, Y, color=”black”)
1 Figures are shown with a graphical user interface that al-
X = np.random.uniform(0, 1, 100) 765 X = np.linspace(0, 10, 100) 765 1234567 lows to zoom and pan the figure, to navigate between the
Y = np.random.uniform(0, 1, 100) 432 Y = np.sin(X) 432 different views and to show the value under the mouse.
ax.scatter(X, Y)
1 ax.plot(X, Y, linestyle=”--”)
1
X = np.arange(10) 765 1234567 X = np.linspace(0, 10, 100) 765 1234567 Save (bitmap or vector format)
Y = np.random.uniform(1, 10, 10) 432 Y = np.sin(X) 432
ax.bar(X, Y)
1 ax.plot(X, Y, linewidth=5)
1 fig.savefig(”my-first-figure.png”, dpi=300)
fig.savefig(”my-first-figure.pdf”)
Z = np.random.uniform(0, 1, (8,8)) 765 1234567 X = np.linspace(0, 10, 100) 765 1234567
432 Y = np.sin(X) 432
1 1
Matplotlib 3.5.0 handout for beginners. Copyright (c) 2021 Matplotlib Development
ax.imshow(Z) ax.plot(X, Y, marker=”o”) Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS.

1234567 1234567

You might also like