类型错误:尝试创建 2 个子图时,“AxesSubplot”对象不可迭代

8 python matplotlib

我试图在同一个输出中创建两个子图。但是我Type Error: 'AxesSubplot' object is not iterable在尝试创建 ax.1 和 ax.2 时得到一个

下面是代码示例以及我尝试执行的操作。

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()                    
Run Code Online (Sandbox Code Playgroud)

我试过.add_subplot()但得到同样的错误?

Bra*_*mon 5

您需要指定

>>> plt.subplots(2, 1, figsize=(8,6))
Run Code Online (Sandbox Code Playgroud)

或者

>>> plt.subplots(1, 2, figsize=(8,6))
Run Code Online (Sandbox Code Playgroud)

否则,只会Axes返回一个,并且您正在尝试对其进行可迭代的解包,这是行不通的。

调用签名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]) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

或者,您可以使用.add_subplot(). 首先创建一个 Figure,然后添加到它:

>>> 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])
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明