0

I have a task that calls a plot numerous times and creates a gif from the results (see below for a reproducible example).

My question is: I would like to add a background image to this gif. My guess is, I would have to add it somewhere in the loop, before appending.

What I found so far, although hilarious did not really relate to my question:

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)

sources:

How to create a DataFrame of random integers with Pandas?

heck1
  • 714
  • 5
  • 20

1 Answers1

1

I don't have a lot of experience with this, but I was able to display the image I called beforehand with plt.imshow(). The demo.gif could not be uploaded due to file size limitations. Sorry, the image used in the sample is not good. Sorry.

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)

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • no need to apologize! solution works fine! problem now: the underlying picture is way too big to fit my points, any ideas for that? – heck1 Aug 12 '20 at 07:17
  • I'm not sure about the size of the image, so I can't say for sure, but does `plt.figure(figsize((10,9), dpi=350)` solve the problem? – r-beginners Aug 12 '20 at 07:22
  • sorry, I think I worded it badly: the underlying image has dimensions of say 1000x2000, yet my datapoints are in the range of 0-100. I just needed to fit my image to that size beforehand and it worked :) – heck1 Aug 12 '20 at 07:29