他,
我在 Julia 中使用 PyPlot 包,遇到了一些我找不到答案的问题。
本质上,我想要一个在迭代计算期间得到更新的绘图窗口。 (我不使用 Atom 的绘图面板,而是使用外部 matplotlib 风格的绘图窗口,带有用于缩放平移等的交互式控件。)
我的代码大致如下
import PyPlot
const plt = PyPlot
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)
...
while (x < y)
... calculation of x and y...
ax1.plot(x)
ax2.plot(y)
end
这或多或少符合预期:最初,会打开一个包含所有子图但没有曲线的窗口。计算运行后,它会绘制我的曲线,我可以看到它们。到目前为止,一切都很好。但是,当计算正在运行时,绘图窗口被锁定,我无法使用“交互式”工具。迭代完成后,它将更新绘图,并且我在“卡住”期间所做的任何输入都将得到执行。但出于实际目的,在我收到回复之前会暂停 10 秒(或更长时间,具体取决于交互需要多长时间)。
有什么方法可以在计算运行时保持窗口响应,还是无法阻止的内置卡住?
感谢您的任何提示,如果它是重复的,我们深表歉意。
最好的, 保利
最佳答案
如果我正确理解你的问题,你可以使用的方法之一是使用 pause
函数:
help?> plt.pause
Pause for *interval* seconds. If there is an active figure, it will be updated and displayed before the pause, and the GUI event loop (if any) will run during the pause. This can be used for crude animation. For more complex animation, see :mod:`matplotlib.animation`. Notes ----- This function is experimental; its behavior may be changed or extended in a future release.
这是一个示例代码:
import PyPlot
const plt = PyPlot
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)
x = rand(1)
y = rand(1)
for i in 1:100
push!(x, rand())
push!(y, rand())
ax1.plot(x)
ax2.plot(y)
plt.pause(0.01)
end
这是你想要的吗?
编辑
如果您的计算成本很高,那么您可以使用多线程来获得您想要的结果。这是一个示例(函数 f
计算量很大,应该在单独的线程中运行):
import PyPlot
function f()
for i in 1:10^9 # just run some expensive task
rand()
end
return rand()
end
const plt = PyPlot
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)
x = rand(1)
y = rand(1)
for i in 1:10
t = Threads.@spawn f()
push!(x, fetch(t))
push!(y, rand())
ax1.plot(x)
ax2.plot(y)
plt.pause(0.0001)
end
关于matplotlib - Julia 和 Pyplot - 窗口锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61576269/