如何在 matplotlib 图的后面叠加图像?

bba*_*oy8 7 python matplotlib

我正在尝试将图像叠加在 matplotlib 图的后面。它在 Flask 网站中以 HTML 形式呈现,因此我在插入之前将绘图保存为图像。没有背景图像的图如下所示:

在此输入图像描述

产生上述输出的代码在这里:

        fname = 'scatter_averages.png'
        url_full = os.path.join(_path_full, fname)
        image = plt.imread("app/static/images/quantum_grid.jpg")
        if os.path.isfile(url_full):
            os.remove(url_full)
        plt.clf()
        df = self.text_numeric_averages()
        if df is not None:
            plt.figure(figsize=(6, 8))
            fig, ax = plt.subplots()
            df.index += 1
            x, y = df.iloc[:, 2], df.iloc[:, 1]
            ax.plot(x, y, '-o')
            plt.xlabel(df.columns[2])
            plt.ylabel(df.columns[1])
            for i in range(len(df)):
                xyi = df.iloc[i, :].values
                ax.annotate(str(df.index[i]) + " " + xyi[0][:3], (xyi[2], xyi[1]))
            axes = plt.gca()
            y_min, y_max = axes.get_ylim()
            x_min, x_max = axes.get_xlim()
            # ax.imshow(image, extent=[x_min, x_max, y_min, y_max])
            plt.savefig(url_full)
Run Code Online (Sandbox Code Playgroud)

上面注释掉的行是我尝试让图像叠加。该行取消注释时的输出如下:

在此输入图像描述

如何保持第一个图像的大小和比例,但使用第二个图中的背景图像作为背景?我不关心图像看起来扭曲。

bba*_*oy8 6

ax.imshow(image, extent=[x_min, x_max, y_min, y_max], aspect="auto")
Run Code Online (Sandbox Code Playgroud)

这会修复它。