Reputation:
I am trying to create two subplots in the same output. But I get a Type Error: 'AxesSubplot' object is not iterable
when trying to create ax.1 and ax.2
Below is an example of the code and what I've tried to do.
import numpy as np
import matplotlib.pyplot as plt
#plot 1 data
x1_data = np.random.randint(80, size=(400, 4))
y1_data = np.random.randint(80, size=(400, 4))
#plot 2 data
x2_data = np.random.randint(80, size=(400, 4))
y2_data = np.random.randint(80, size=(400, 4))
fig, (ax1, ax2) = plt.subplots(figsize = (8,6))
#scatter plot 1
scatter1 = ax1.scatter(x1_data[0], y1_data[0])
#scatter plot 2
scatter2 = ax2.scatter(x2_data[0], y2_data[0])
plt.draw()
I tried .add_subplot()
but get the same error?
Upvotes: 10
Views: 43086
Reputation: 40888
You'll need to specify either
>>> plt.subplots(2, 1, figsize=(8,6))
or
>>> plt.subplots(1, 2, figsize=(8,6))
Otherwise, only one Axes
is returned, and you are trying to do iterable unpacking on it, which won't work.
The call signature is subplots(nrows=1, ncols=1, ...)
.
>>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 6))
>>> scatter1 = ax1.scatter(x1_data[0], y1_data[0])
>>> scatter2 = ax2.scatter(x2_data[0], y2_data[0])
Alternatively, you could use .add_subplot()
. First create a Figure, then add to it:
>>> fig = plt.figure(figsize=(8, 6))
>>> ax1 = fig.add_subplot(211)
>>> ax2 = fig.add_subplot(212)
>>> ax1.scatter(x1_data[0], y1_data[0])
>>> ax2.scatter(x2_data[0], y2_data[0])
Upvotes: 7