如何在 matplotlib 绘图的背景上叠加一张图片?

7

我正在尝试在matplotlib图形的后面叠加一张图片。它作为HTML在flask网站中呈现,因此我要先将绘图保存为图像再插入它。没有背景图像的绘图如下所示:

enter image description here

产生上述输出的代码在此处:

        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)

上面被注释的那一行是我尝试叠加图像的方法。当取消注释时,输出结果如下:

enter image description here

我该如何保持第一张图像的大小比例并使用第二张图像作为背景?我不关心图像看起来是否会变形。
1个回答

6
ax.imshow(image, extent=[x_min, x_max, y_min, y_max], aspect="auto")

这样做可以解决问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接