Figure and Axes
We can then use
axs.plot to draw some data.

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
fig, axs = plt.subplots(1, 2)
np.random.seed(100000000)
data = {
'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50),
}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fix, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('a')
ax.set_ylabel('b')
plt.show()
Usage Styles
There are essentially
two ways to use Matplotlib.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2, 100)
fix, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.legend()
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()
Annotations
We can also annotate
points on a plot

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2 * np.pi * x)
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(x, y, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='gray', shrink=0.05))
ax.set_ylim(-2, 2)
plt.show()
Annotations (plt)
Annotations when using
plt scatter() function.

import matplotlib.pyplot as plt
xa = [1, 2, 3, 4]
ya = [5, 6, 7, 8]
plt.scatter(xa, ya, color='r', marker='x')
for i, p in enumerate(zip(xa, ya)):
plt.annotate(f"({p[0]}, {p[1]})", (p[0]+0.1, p[1]-.1))
plt.show()
Additional axis
Use
twinx to add a new Axes with an invisible x-axis.

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2 * np.pi * x)
l1, = ax.plot(x, y)
ax2 = ax.twinx()
l2, = ax2.plot(x, range(len(x)), 'C1')
plt.show()
Colored map
Often we want to have a
third dimension in a plot.

import matplotlib.pyplot as plt
import numpy as np
X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128))
Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2)
fig, ax = plt.subplots()
co = ax.contourf(X, Y, Z, levels=np.linspace(-1.25, 1.25, 11))
fig.colorbar(co)
ax.set_title('contourf()')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
