Skip to content

Instantly share code, notes, and snippets.

@markusrenepae
Last active December 29, 2019 21:48
Show Gist options
  • Save markusrenepae/cab2e677de40e621abc8893ed6e01c9a to your computer and use it in GitHub Desktop.
Save markusrenepae/cab2e677de40e621abc8893ed6e01c9a to your computer and use it in GitHub Desktop.
This gist is for my medium article about creating GIF images.
import imageio
import os
import matplotlib.pyplot as plt
lst1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
lst2 = [5, 4, 3, 5, 6, 5, 8, 7, 8, 10, 5, 6]
lst3 = [9, 6, 6, 7, 6, 4, 6, 9, 11, 8, 7, 4]
def createfiles():
for i in range(1, 25):
if i > 12:
stopidx = 12
else:
stopidx = i
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
plt.yticks((1, 3, 5, 7, 9, 11, 13))
ax.set_xticklabels([])
ax.set(xlim=(0.5, 12.5), ylim=(0.000001, 13.99999))
ax.plot(lst1[:stopidx], lst2[:stopidx], color="red")
ax.plot(lst1[:stopidx], lst3[:stopidx], color="green")
plt.savefig("img"+"{:02d}".format(int(i))+".png")
def deletefiles():
for i in range(1, 25):
os.remove("img"+"{:02d}".format(int(i))+".png")
def creategif():
path = 'C:/path/to/file'
image_folder = os.fsencode(path)
filenames = []
for file in os.listdir(image_folder):
filename = os.fsdecode(file)
if filename.endswith(('.jpeg', '.png')):
filenames.append(path+filename)
filenames.sort() # this iteration technique has no built in order, so sort the frames
images = list(map(lambda filename: imageio.imread(filename), filenames))
imageio.mimsave(os.path.join('example.gif'), images, duration = 0.5)
plt.rc('figure', max_open_warning = 0)
createfiles()
creategif()
deletefiles()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment