Home » Machine Learning » Plotting » Subplots

Subplots

Matplotlib has a really nice syntax for plotting multiple plots side-by-side or in a grid in the same window.

Since this syntax is so elegant, it’s common to use it even when you just want one plot. Then you can use a consistent syntax however many plots you need.

Single Plots with the Subplot API

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y = np.sin(x)

fig = plt.figure()
ax = fig.add_subplot()

# Set the overall title
ax.set_title("Trig Functions")

# Set the axis labels
ax.set_xlabel("x")
ax.set_ylabel("Trig function value")

ax.plot(x, y, color='red')

plt.show()

Multiple Subplots

We can add multiple subplots to the same plot window by supplying arguments to add_subplot. These are numbers that specify how many rows of plots we want, how many columns, and the position of the current plot within the grid (plots start numbering at 1).

So add_subplot(2,3,4) or add_subplot(234) both mean that we want to add the fourth plot in a grid of plots that consists of 2 rows and 3 columns.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y1 = np.cos(x)

# the figsize param lets us set the window size.
fig = plt.figure(figsize=(16,9))

# Set the super-title (overall title)
fig.suptitle("Trig Functions")

ax = fig.add_subplot(121)
ax.set_title("sin")
ax.set_xlabel("x")
ax.set_ylabel("y=sin(x)")
ax.plot(x, y1, color='red')

ax = fig.add_subplot(122)
ax.set_title("cos")
ax.set_xlabel("x")
ax.set_ylabel("y=cos(x)")
ax.plot(x, y1, color='green')

plt.show()

Another way to create the exact same chart is to use the subplots method of Pyplot. If nrows or ncols are set to something other than 1, this then returns an array of axes that can be used to draw the subplots.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y1 = np.cos(x)

# the figsize param lets us set the window size.
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(16,9))

# Set the super-title (overall title)
fig.suptitle("Trig Functions")

ax = axes[0]
ax.set_title("sin")
ax.set_xlabel("x")
ax.set_ylabel("y=sin(x)")
ax.plot(x, y1, color='red')

ax = axes[1]
ax.set_title("cos")
ax.set_xlabel("x")
ax.set_ylabel("y=cos(x)")
ax.plot(x, y1, color='green')

plt.show()

Leave a Reply

Blog at WordPress.com.

%d