Skip to content

Matplotlib

Programming / python

Hello matplotlib

1
2
3
4
5
6
import matplotlib.pyplot as plt
import numpy as np 

fig, ax = plt.subplots()             # Create a figure containing a single Axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])  # Plot some data on the Axes.
plt.show()    

alt text


Figure

alt text

The whole figure. The Figure keeps track of all the child Axes, a group of 'special' Artists (titles, figure legends, colorbars, etc.), and even nested subfigures.

Axes

An Axes is an Artist attached to a Figure that contains a region for plotting data, and usually includes two (or three in the case of 3D) Axis objects

Axis

Artist



figure and subplots

import matplotlib.pyplot as plt
import numpy as np 

fig, axs = plt.subplots(2, 2, figsize=(4, 3), layout='constrained')
for row in range(2):
    for col in range(2):
        axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5),
                            transform=axs[row, col].transAxes,
                            ha='center', va='center', fontsize=18,
                            color='darkgrey')
# ax.plot([1, 2, 3, 4], [1, 4, 2, 3])  # Plot some data on the Axes.
plt.show()

alt text

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(2, 2, figsize=(4, 3), layout="constrained")

x, y = [1, 2], [4, 5]

ax = axs[0, 0]
linesx = ax.scatter(x, y)

ax = axs[0, 1]
linesx = ax.plot(x, y)

ax = axs[1, 0]
linesx = ax.bar(x, y)

ax = axs[1, 1]
img_2d_array = np.random.rand(10, 10)
linesx = ax.imshow(img_2d_array)

plt.show()

alt text