python - matplotlib savefig 线程安全吗?

标签 python multithreading matplotlib plot

我有一个内部分布式计算库,我们一直使用它来处理并行计算作业。进程分区后,它们运行数据加载和计算步骤,然后以“保存”步骤结束。通常这涉及将数据写入数据库表。

但对于特定任务,我需要每个过程的输出是一个包含一些数据图的 .png 文件。总共有 95 个进程,所以 95 个 .png。

在我的“保存”步骤(在每个进程上执行)中,我有一些非常简单的代码,使用 matplotlib 的 boxplot 函数和一些使用 savefig 的代码制作箱线图> 将其写入具有基于该过程中使用的特定数据的唯一名称的 .png 文件。

但是,我偶尔会在输出中看到两组或更多组数据被写入同一个输出文件,尽管名称是唯一的。

matplotlib 在制作箱线图或保存图形时是否使用临时文件保存?如果是这样,它是否总是使用相同的临时文件名(从而导致覆盖冲突)?我已经使用 strace 运行我的进程,但看不到任何明显看起来像从 matplotlib 写入临时文件的内容。

我如何确保这将是线程安全的?我绝对想并行进行文件保存,因为我希望大大扩展输出 .png 的数量,所以首先存储所有数据然后连续执行绘图/保存部分的选项是非常不可取的。

我不可能重现我们正在使用的完整并行基础设施,但下面是被调用以创建绘图句柄的函数,然后是被调用以保存绘图的函数。为了这个问题,您应该假设线程安全与我们的分布式库无关。我们知道它不是来 self 们的代码,这些代码多年来一直用于我们的多处理作业,没有像这样的线程问题(特别是对于我们不直接控制的东西,比如来自 matplotlib 的任何临时文件)。

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

def plot_category_data(betas, category_name):
    """
    Function to organize beta data by date into vectors and pass to box plot
    code for producing a single chart of multi-period box plots.
    """
    beta_vector_list = []
    yms = np.sort(betas.yearmonth.unique())
    for ym in yms:
        beta_vector_list.append(betas[betas.yearmonth==ym].Beta.values.flatten().tolist())
    ###

    plot_output = plt.boxplot(beta_vector_list)
    axs = plt.gcf().gca()
    axs.set_xticklabels(betas.FactorDate.unique(), rotation=40, horizontalalignment='right')
    axs.set_xlabel("Date")
    axs.set_ylabel("Beta")
    axs.set_title("%s Beta to BMI Global"%(category_name))
    axs.set_ylim((-1.0, 3.0))

    return plot_output
### End plot_category_data

def save(self):
    """
    Make calls to store the plot to the desired output file.
    """
    out_file = self.output_path + "%s.png"%(self.category_name)
    fig = plt.gcf()
    fig.set_figheight(6.5)
    fig.set_figwidth(10)
    fig.savefig(out_file, bbox_inches='tight', dpi=150)
    print "Finished and stored output file %s"%(out_file)
    return None
### End save

最佳答案

在您的两个函数中,您正在调用 plt.gcf()。每次您使用 plt.figure() 绘图并明确引用该图形时,我都会尝试生成一个新图形,这样您就可以完全避开整个问题。

关于python - matplotlib savefig 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14586764/

相关文章:

java - 根据输入的数量在 while 循环中创建多个 java 线程

iOS - 如何测量线程唤醒?

python - 在 Python 中制作表格的最简单方法是什么?

python - 更改颜色条宽度

python - Windows 上的 Apache Zeppelin : error creating python interpreter

python检查单词是否在列表的某些元素中

python - 搜索后端错误 : No fields were found in any search_indexes

PYTHON:打开 csv 文件并查找列中的最大数字以及与其关联的名称的最简单方法?

java - 使用 SwingUtilities.invokeLater 专注于 JDialog?

在导入 swig 生成的包装器的模块中使用 matplotlib 绘图时 Python 崩溃