Matplotlib:有没有一种方法可以让我们在 Python 处理 `.show()` 之后的例程时查看和处理绘图结果?
Matplotlib: Is there a way so that we can see and work with plot result while the routines after the `.show()` is being processed by Python?
有没有一种方法可以让我们在 Python 处理 fig.show()
之后的例程时查看和处理绘图结果(图形和轴)?
例如,运行 下面的代码,Python 在处理 for 循环时显示图形 window 但不显示绘图(它只显示白色背景,滞后) .只有在整个代码完成后,我才能看到情节并与之交互。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3]); fig.show()
#I want the plot to be visible and explorable,
# while the for loop below is in process (or any other kind of routine)
for i in range(10000):
print(i)
结果截图(可以看到剧情滞后,只有空白):
您可以结合使用单独的 python 过程(通过 multiprocessing) and the blocking behaviour of plt.show() 达到预期结果:
import matplotlib.pyplot as plt
import time
from multiprocessing import Process
def show_plot(data):
fig, ax = plt.subplots()
ax.plot(data)
plt.show()
def do_calculation():
for i in range(100):
print(i)
time.sleep(0.1)
if __name__ == '__main__':
p = Process(target=show_plot, args=([1,2,3],))
p.start() # start parallel plotting process
do_calculation()
p.join() # the process will terminate once the plot has been closed
有没有一种方法可以让我们在 Python 处理 fig.show()
之后的例程时查看和处理绘图结果(图形和轴)?
例如,运行 下面的代码,Python 在处理 for 循环时显示图形 window 但不显示绘图(它只显示白色背景,滞后) .只有在整个代码完成后,我才能看到情节并与之交互。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3]); fig.show()
#I want the plot to be visible and explorable,
# while the for loop below is in process (or any other kind of routine)
for i in range(10000):
print(i)
结果截图(可以看到剧情滞后,只有空白):
您可以结合使用单独的 python 过程(通过 multiprocessing) and the blocking behaviour of plt.show() 达到预期结果:
import matplotlib.pyplot as plt
import time
from multiprocessing import Process
def show_plot(data):
fig, ax = plt.subplots()
ax.plot(data)
plt.show()
def do_calculation():
for i in range(100):
print(i)
time.sleep(0.1)
if __name__ == '__main__':
p = Process(target=show_plot, args=([1,2,3],))
p.start() # start parallel plotting process
do_calculation()
p.join() # the process will terminate once the plot has been closed