PHOT 110: Introduction to programming

LECTURE 09: Plots and visualizations (Ch. 5)

Michaël Barbier, Spring semester (2023-2024)

Plotting with Matplotlib

Basic plotting

# Import library for plotting and numerics
import numpy as np
import matplotlib.pyplot as plt

# Define x and y coordinates
x = np.linspace(-2, 2, 100)
y = x**2

# Plot a line between the coordinates
plt.plot(x, y)

Basic plotting

A Matplotlib figure

  • Figure handle
  • Figure size
  • Subplots
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,5))
plt.show()

A Matplotlib figure

A Matplotlib figure

Creating a curve in the axes

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi*x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

A Matplotlib figure

A Matplotlib figure

  • Multiple plots
  • Multiple curves in a single axes
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi*x)

fig, ax = plt.subplots(1, 2) # Two columns
ax[0].plot(x, y)
ax[1].plot(x, y**2)
ax[1].plot(x, 1/(y+2))
plt.show()

A Matplotlib figure

A Matplotlib figure

Subplots: multiple rows and columns

import matplotlib.pyplot as plt
import numpy as np

# Data for the plots
x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi*x)

# Plotting
fig, ax = plt.subplots(2, 3)  # 2 rows, 3 cols
ax[0, 2].plot(x, y)
ax[1, 0].plot(x, 2-y)
plt.show()

A Matplotlib figure

Parts of a plot

  • Actual data:
    • Curves, points,
    • surfaces, etc.
  • Axes, limits, aspect ratio
  • Grids and thickmarks
  • Title, Axis labels
  • Legend

Start from Matplotlib.org

There are many options !

  • Different plot types.
  • Many plot characteristics that can be changed.
  • Animations.
  • Good starting points: the Matplotlib website

Starting with Matplotlib

Matplotlib plot types