Fab*_*ian 12 python plot multithreading matplotlib
我知道在matplotlib和线程上有很多问题,而且pyplot也不是线程.然而,我无法找到关于这个特定问题的任何内容.我想要做的是:绘制一个数字并每秒更新一次.为此,我想创建一个线程,但到目前为止,我甚至无法从线程中获得真实的情节.此外,我坚持使用qt4,因此可能是其他后端表现不同.
这是一个非常简单的例子:创建了一个图plot_a_graph().从主程序调用时,这可以正常工作,但会延迟主代码的进一步执行.但是,从线程调用时,不会显示任何图形.
import matplotlib
matplotlib.use("qt4agg")
import matplotlib.pyplot as plt
import threading
import time
def plot_a_graph():
    f,a = plt.subplots(1)
    line = plt.plot(range(10))
    plt.show()
    print "plotted graph"    
    time.sleep(4)
testthread = threading.Thread(target=plot_a_graph)
plot_a_graph()      # this works fine, displays the graph and waits
print "that took some time"
testthread.start() # Thread starts, window is opened but no graph appears
print "already there"
谢谢你的帮助
我的建议是使用python 多处理模块而不是线程模块.我已经能够对您的示例代码执行轻微修改,并成功地将matplotlib绘图卸载到子进程,同时主进程中的控制流继续(请参阅下面的代码).
如果您希望子进程在更大的代码控制流程的上下文中与父进程进行来回通信,我建议您阅读多处理文档或有关该主题的任何大量博客文章(这不是'在你的问题中完整描述).请注意,多处理具有额外的优势,可以绕过python 全局解释器锁并允许您利用多核计算机体系结构.
#a slight modification of your code using multiprocessing
import matplotlib
matplotlib.use("qt4agg")
import matplotlib.pyplot as plt 
#import threading
#let's try using multiprocessing instead of threading module:
import multiprocessing
import time
#we'll keep the same plotting function, except for one change--I'm going to use the multiprocessing module to report the plotting of the graph from the child process (on another core):
def plot_a_graph():
    f,a = plt.subplots(1)
    line = plt.plot(range(10))
    print multiprocessing.current_process().name,"starting plot show process" #print statement preceded by true process name
    plt.show() #I think the code in the child will stop here until the graph is closed
    print multiprocessing.current_process().name,"plotted graph" #print statement preceded by true process name
    time.sleep(4)
#use the multiprocessing module to perform the plotting activity in another process (i.e., on another core):
job_for_another_core = multiprocessing.Process(target=plot_a_graph,args=())
job_for_another_core.start()
#the follow print statement will also be modified to demonstrate that it comes from the parent process, and should happen without substantial delay as another process performs the plotting operation:
print multiprocessing.current_process().name, "The main process is continuing while another process deals with plotting."