要使matplotlib绘图成为一个函数而不阻止执行,我遇到了问题。
我试过像一些人建议的那样使用show(block=False),但我得到的只是一个冻结的窗口。如果我只调用show(),结果就会被正确地绘制出来,但是执行会被阻塞,直到窗口关闭为止。从我读过的其他线程中,我怀疑show(block=False)是否工作取决于后端。这是正确的吗?我的后端是Qt4Agg。你能看看我的代码然后告诉我如果你发现了什么问题吗?这是我的密码。
from math import *
from matplotlib import pyplot as plt
print(plt.get_backend())
def main():
x = range(-50, 51, 1)
for pow in range(1,5): # plot x^1, x^2, ..., x^4
y = [Xi**pow for Xi in x]
print(y)
plt.plot(x, y)
plt.draw()
#plt.show() #this plots correctly, but blocks execution.
plt.show(block=False) #this creates an empty frozen window.
_ = raw_input("Press [enter] to continue.")
if __name__ == '__main__':
main()PS。我忘了说,我想要更新现有的窗口,每次我的计划,而不是创建一个新的窗口。
发布于 2015-10-10 05:22:46
我花了很长时间寻找解决方案,并找到了这个答案。
看起来,为了得到您(和我)想要的东西,您需要plt.ion()、plt.show() (而不是与block=False)以及最重要的是plt.pause(.001) (或任何您想要的时间)的组合。需要暂停是因为GUI是在主代码休眠时发生的,包括绘图。这有可能是通过从休眠线程中抽出时间来实现的,所以也许IDE会处理这个问题--我不知道。
下面是我在python 3.5上使用的一个实现:
import numpy as np
from matplotlib import pyplot as plt
def main():
plt.axis([-50,50,0,10000])
plt.ion()
plt.show()
x = np.arange(-50, 51)
for pow in range(1,5): # plot x^1, x^2, ..., x^4
y = [Xi**pow for Xi in x]
plt.plot(x, y)
plt.draw()
plt.pause(0.001)
input("Press [enter] to continue.")
if __name__ == '__main__':
main()发布于 2017-03-08 14:45:24
一个对我有用的简单技巧是:
示例
import matplotlib.pyplot as plt
plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")
plt.show(block=False)
#more code here (e.g. do calculations and use print to see them on the screen
plt.show()plt.show()是我脚本的最后一行。
发布于 2018-04-01 02:30:35
通过将绘图写入数组,然后将数组显示在不同的线程中,可以避免阻止执行。下面是一个使用pf.screen从公式0.2.8同时生成和显示图形的示例
import pyformulas as pf
import matplotlib.pyplot as plt
import numpy as np
import time
fig = plt.figure()
canvas = np.zeros((480,640))
screen = pf.screen(canvas, 'Sinusoid')
start = time.time()
while True:
now = time.time() - start
x = np.linspace(now-2, now, 100)
y = np.sin(2*np.pi*x) + np.sin(3*np.pi*x)
plt.xlim(now-2,now+1)
plt.ylim(-3,3)
plt.plot(x, y, c='black')
# If we haven't already shown or saved the plot, then we need to draw the figure first...
fig.canvas.draw()
image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
screen.update(image)
#screen.close()结果:

免责声明:我是编写公式的维护者。
https://stackoverflow.com/questions/28269157
复制相似问题