python - Matplotlib:在多个线程中同时绘图

标签 python multithreading matplotlib python-multithreading

我正在尝试并行进行一些绘图以更快地完成大批量作业。为此,我为我计划制作的每个情节都创建了一个线程。

我曾希望每个线程都能完成其绘图并自行关闭(据我了解,Python 在线程完成 run() 中的所有语句时会关闭线程)。下面是一些显示这种行为的代码。

如果创建图形的行被注释掉,它将按预期运行。另一个似乎很有帮助的花絮是,当您只生成一个线程时,它也会按预期运行。

import matplotlib.pyplot as plt
import time
import Queue
import threading

def TapHistplots():
    ##  for item in ['str1']:
# # it behaves as expected if the line above is used instead of the one below
    for item in ['str1','str2']:
        otheritem = 1
        TapHistQueue.put((item, otheritem))
        makeTapHist().start()

class makeTapHist(threading.Thread):
    def run(self):
        item, otheritem = TapHistQueue.get()
        fig = FigureQueue.get()
        FigureQueue.put(fig+1)
        print item+':'+str(fig)+'\n',
        time.sleep(1.3)
        plt.figure(fig) # comment out this line and it behaves as expected
        plt.close(fig)

TapHistQueue = Queue.Queue(0)
FigureQueue = Queue.Queue(0)
def main():
    start = time.time()
    """Code in here runs only when this module is run directly"""
    FigureQueue.put(1)
    TapHistplots()
    while threading.activeCount()>1:
        time.sleep(1)
        print 'waiting on %d threads\n' % (threading.activeCount()-1),
    print '%ds elapsed' % (time.time()-start)

if __name__ == '__main__':
    main()

非常感谢任何帮助。

最佳答案

为什么不直接使用多处理?据我从你的描述中可以看出,无论如何,线程对你没有多大帮助......

Matplotlib 已经线程化,因此您可以一次显示多个图形并与之交互。如果你想在多核机器上加速批处理,无论如何你都需要多处理。

作为一个基本示例(警告:这将在您运行它的任何目录中创建 20 个小的 .png 文件!)

import multiprocessing
import matplotlib.pyplot as plt
import numpy as np

def main():
    pool = multiprocessing.Pool()
    num_figs = 20
    input = zip(np.random.randint(10,1000,num_figs), 
                range(num_figs))
    pool.map(plot, input)

def plot(args):
    num, i = args
    fig = plt.figure()
    data = np.random.randn(num).cumsum()
    plt.plot(data)
    plt.title('Plot of a %i-element brownian noise sequence' % num)
    fig.savefig('temp_fig_%02i.png' % i)

main()

关于python - Matplotlib:在多个线程中同时绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4659680/

相关文章:

python - 如何将 seaborn/matplotlib 轴刻度标签从数字格式化为数千或数百万? (125,436 至 125.4K)

python - 同一页面上的重复占位符

c# - 将变量添加到另一个线程正在使用的列表中,这是不好的做法吗?

Java的最大线程数非常有限?

c++ - 线程写入日志文件

python-3.x - Seaborn 设置 figsize=(x,y) 关于 tight_layout "tight_layout cannot make axes height small enough to accommodate all axes decorations"的错误和警告

python - 如何使用 python 从进程中获取原始命令行?

python - PyQt QDialog 返回响应是或否

python - 在 Python 中模拟套接字连接

matplotlib - 更改 View 、plot3D、Julia 语言(类似于 matplotlib)