我试图在同一输出中创建两个子图。但是当尝试创建ax.1和ax.2时我得到了Type Error: 'AxesSubplot' object is not iterable
下面是代码示例以及我尝试执行的操作。

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

我尝试了.add_subplot(),但是得到了同样的错误?

最佳答案

您需要指定

>>> plt.subplots(2, 1, figsize=(8,6))

或者
>>> plt.subplots(1, 2, figsize=(8,6))

否则,将仅返回一个Axes,并且您正在尝试对其进行可迭代的解压缩,这将无法正常工作。

call signaturesubplots(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])

python - TypeError :  'AxesSubplot'  object is not iterable when trying to create 2 subplots-LMLPHP

另外,您可以使用.add_subplot()。首先创建一个图,然后添加到它:
>>> 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])

python - TypeError :  'AxesSubplot'  object is not iterable when trying to create 2 subplots-LMLPHP

关于python - TypeError : 'AxesSubplot' object is not iterable when trying to create 2 subplots,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49246747/

10-13 00:02