【问题标题】:Add a background image to matplotlib plot / gif将背景图像添加到 matplotlib plot / gif
【发布时间】:2020-12-01 21:24:19
【问题描述】:

我有一个任务会多次调用一个绘图并根据结果创建一个 gif(请参阅下面的可重现示例)。

我的问题是:我想为这个 gif 添加背景图片。我的猜测是,在附加之前,我必须在循环中的某个位置添加它。

到目前为止,我发现了什么,虽然很搞笑并与我的问题没有真正的关系:

Plotting a cropped background image on a matplotlib graph

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter
import time

rng = np.random.default_rng()
fig = plt.figure(figsize=[10, 9])

ims = []
for i in range(200):
    df = pd.DataFrame(rng.integers(0, 100, size=(100, 2)), columns=list('xy'))
    x = df["x"]
    y = df["y"]
    im = plt.plot(x, y, "b.")
    ims.append(im)
    print(i)
    
    
    

ani = animation.ArtistAnimation(fig, ims, interval=500, blit=True,
                                repeat_delay=1000)

writer = PillowWriter(fps=2)
ani.save("demo2.gif", writer=writer)

来源:

How to create a DataFrame of random integers with Pandas?

【问题讨论】:

    标签: python matplotlib gif


    【解决方案1】:

    我对此没有太多经验,但我能够显示我事先用plt.imshow() 调用的图像。由于文件大小限制,无法上传 demo.gif。抱歉,示例中使用的图像不好。对不起。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    from matplotlib.animation import PillowWriter
    import time
    import matplotlib.image as mpimg
    
    rng = np.random.default_rng()
    fig = plt.figure(figsize=[10, 9])
    
    img = mpimg.imread('lena_thumbnail_center_square.jpg')
    
    ims = []
    for i in range(200):
        df = pd.DataFrame(rng.integers(0, 100, size=(100, 2)), columns=list('xy'))
        x = df["x"]
        y = df["y"]
        im = plt.plot(x, y, "b.")
        ims.append(im)
    #     print(i)   
    
    ani = animation.ArtistAnimation(fig, ims, interval=500, blit=True,
                                    repeat_delay=1000)
    plt.imshow(img)
    
    writer = PillowWriter(fps=2)
    ani.save("demo2.gif", writer=writer)
    

    【讨论】:

    • 无需道歉!解决方案工作正常!现在的问题:底层图片太大了,不适合我的观点,有什么想法吗?
    • 我不确定图片的大小,所以不能肯定,但是plt.figure(figsize((10,9), dpi=350)能解决问题吗?
    • 抱歉,我认为我措辞不好:底层图像的尺寸为 1000x2000,但我的数据点在 0-100 范围内。我只需要事先将我的图像调整到那个尺寸就可以了:)
    猜你喜欢
    • 2013-02-16
    • 2021-10-14
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2012-04-09
    • 2011-06-01
    • 2017-01-14
    相关资源
    最近更新 更多