gpt4 book ai didi

python - 类型错误 : 'AxesSubplot' object is not iterable when trying to create 2 subplots

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:41 25 4
gpt4 key购买 nike

我正在尝试在同一输出中创建两个子图。但是我在尝试创建 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])

enter image description here

或者,您可以使用 .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])

enter image description here

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com