Programming

  minte9
LearnRemember



Matplotlib / Subplots


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()





References