【问题标题】:Matplotpib figure in a loop not responding循环中的 Matplotlib 图没有响应
【发布时间】:2017-01-31 08:15:21
【问题描述】:

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

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

那么我在这里错过了什么?

编辑:考虑到下面水生挑战的答案。这些数字仍然挂起,直到退出循环,然后它们都被同时绘制。任何人都知道为什么情节没有在循环内完成?

【问题讨论】:

  • 在 Mac 上的 python 2.7 中运行它,我无法复制您的问题。我确实遇到的一个问题是 number 需要转换为 int 才能运行脚本。除此之外,这段代码对我来说似乎运行良好。

标签: python numpy matplotlib


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我没有复制,但是当您输入'y''n' 时。尝试把单(或双引号)是yn

    输入不带引号的字符串。使用raw_input 而不是input

    如此处所述Python 2.7 getting user input and manipulating as string without quotations

    【讨论】:

    • 是的,有效,知道为什么情节在等待输入时挂起吗?
    • 事实上,如果我继续输入'y',所有的数字都会启动,但在输入'n'退出循环之前,它们都不会绘制
    猜你喜欢
    • 2021-07-09
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多