简体   繁体   English

如何在 matplotlib plot 的背面叠加图像?

[英]How do I superimpose an image in the back of a matplotlib plot?

I'm trying to superimpose an image in the back of a matplotlib plot. It is being rendered as HTML in a flask website so I am saving the plot as an image before inserting it.我正在尝试在 matplotlib plot 的背面叠加图像。它在 flask 网站中呈现为 HTML,因此我在插入之前将 plot 保存为图像。 The plot without the background image looks like this:没有背景图片的 plot 看起来像这样:

在此处输入图像描述

The code that produces the above output is here:产生上述 output 的代码在这里:

        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)

The commented out line above is my attempt to get the image to superimpose.上面注释掉的行是我试图让图像叠加。 The output when that line is uncommented is this:取消注释该行时的 output 是这样的:

在此处输入图像描述

How do I keep the sizing and scale of the first image but use the background image in the second plot as the background?如何保持第一张图片的大小和比例,但使用第二张 plot 中的背景图片作为背景? I'm not concerned with the image looking distorted.我不关心看起来扭曲的图像。

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

This will fix it.这将解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM