gpt4 book ai didi

python - Matplotlib 循环中的图形没有响应

转载 作者:行者123 更新时间:2023-12-01 03:40:58 25 4
gpt4 key购买 nike

Python 2.7.11、Win 7、x64、Numpy 1.10.4、matplotlib 1.5.1

在命令行输入 %matplotlib qt 后,我从 iPython 控制台运行了以下脚本

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np

number = input("Number: ")
coords = np.array(np.random.randint(0, number, (number, 3)))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(coords[:,0], coords[:,1], coords[:,2])
plt.show()

它绘制了 3D 随机散布图。因此,我认为将其放入 while 循环并在每次迭代中获取一个新数字将是一件微不足道的事情。

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np

s = True
while s:

number = input("Number: ")
coords = np.array(np.random.randint(0, number, (number, 3)))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(coords[:,0], coords[:,1], coords[:,2])
plt.show()
cont = input("Continue? (y/n)")
if cont == 'n':
s = False

...但数字只是空白且无响应,直到我输入 cont 然后我得到,

NameError: name 'y' is not defined

...整个事情都崩溃了。

那么我在这里缺少什么?

编辑:考虑到下面的水上挑战的答案。这些数字仍然挂起,直到退出循环,然后它们全部同时绘制。有人知道为什么绘图不在循环内完成吗?

最佳答案

input尝试 eval您输入的字符串,将其视为 Python 代码,然后返回计算结果。例如,如果 result = input() 并且我输入 2 + abs(-3)result 将等于 5.

当您输入字符串y时,它将被视为变量名称。由于您尚未定义任何名为 y 的变量,您将收到 NameError。您想要使用 raw_input 而不是 input ,它只返回输入字符串而不尝试对其求值。

<小时/>

为了让图形在 while 循环中显示,您需要插入一个短暂的暂停,以便在继续执行 while 循环之前绘制图形的内容。您可以使用 plt.pause ,它还负责更新事件图形。

s = True
while s:

number = input("Number: ")
coords = np.array(np.random.randint(0, number, (number, 3)))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(coords[:,0], coords[:,1], coords[:,2])
plt.pause(0.1)

cont = raw_input("Continue? (y/n)")
if cont == 'n':
s = False

关于python - Matplotlib 循环中的图形没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39644336/

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