MLearning
/
Matplotlib
- 1 Supervised 7
-
Classifier S
-
Linear model S
-
Basis expansion S
-
Regularization S
-
Decision tree S
-
Random forest S
-
Logistic regression S
- 2 Datasets 5
-
Iris species S
-
Diabetes S
-
Breast cancer S
-
Simulated data S
-
Tmdb S
- 3 Numpy 4
-
Matrices S
-
Operations S
-
Standard deviation S
-
Multiplication S
- 4 Pandas 5
-
Read data S
-
Data cleaning S
-
Find values S
-
Group rows S
-
Merge S
- 5 Matplotlib 2
-
Subplots S
-
Pyplot S
- 6 Algorithms 4
-
K nearest neighbors S
-
Linear regression S
-
Gradient descent S
-
Decision tree S
- 7 Calculus 2
-
Derivatives S
-
Integrals S
S
R
Q
ML Matplotlib Subplots
Matplotlib graphs your data on Figure Each figure can contain one or more Axes fig, ax = plt.subplots() ax.plot([1, 2]) # line
Figure and Axes
We can then use axs.plot to draw some data.
"""
Simple line, subplots, bubbles
"""
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # Figure with single axes
# Lines
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # [x1, x2, x3, x4], [y1, ...
# Subplots
fig, axs = plt.subplots(1, 2) # Figure with 2x2 grid of axes
# Bubbles
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) # s=size, c=color
ax.set_xlabel('a')
ax.set_ylabel('b')
plt.show()



Usage Styles
There are essentially two ways to use Matplotlib.
""" Tow ways of using Matplotlib
Explicitly create Figures and Axes, and call methods on them (OOP) and ...
Rely on pyplot to create and manage Figures and Axes, end use functions
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2, 100)
# OOP style
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()
# Pyplot style
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
"""
Annotate points on 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.
""" Annotations (when using plt.scatter)
"""
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.
"""
Plotting data of different magnitude in one chart
may require an additional y-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() # invisible x-ax
l2, = ax2.plot(x, range(len(x)), 'C1')
plt.show()

Colored map
Often we want to have a third dimension in a plot.
"""
Third dimension in a plot represented by a colors in a colormap
"""
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()

➥ Questions