Trying to create an animated GIF with static images obtained from the seaborn library. The code is as follows:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import imageio.v3 as iio
image = []
folder = 'C:/Users/admin/PycharmProjects/pythonProject2/Project/Seaborn'
if not os.path.exists(folder):
os.mkdir(folder)
for month in range(1, 4):
porosity_cutoff = 250
highlight_colour = 8
non_highlight_colour = 10
df = pd.read_csv('../Список.csv')
df = df.loc[df['Месяц'] == month].sort_values(by='Баллы', ascending=False)
df['colours'] = df["Баллы"].apply(lambda x: highlight_colour if x >= porosity_cutoff else non_highlight_colour)
ax = sns.barplot(data=df.loc[df['Месяц'] == month], x="Баллы", y="Участники", palette="Set1", hue=df['colours'],
legend=False)
plt.axvline(x=250, zorder=0, color='grey', ls='--', lw=1.5)
plt.text(x=283, y=8, s='Порог допустимых баллов', ha='center', fontsize=11, bbox=dict(facecolor='white',
edgecolor="grey", ls='--'))
ax.set_title(f"Рейтинг за {month} месяц", size=30)
ax.set_ylabel("Участники", size=20)
ax.set_xlabel("Баллы", size=20)
for i in ax.containers:
ax.bar_label(i, color="white", padding=-30, fontsize=12)
filename = f'Рейтинг_{month}.png'
plt.savefig(filename)
image.append(iio.imread(filename))
plt.close()
iio.imwrite('barplot.gif', image, duration=20)
In the end I get three images in png format with graphics, all the images are correct, but the giftcard itself is a static first graph. What can be changed or does not work in general?
Guess it’s about the list image and filling it out wrong
I can create animated gif without problem.
Problem can be only duration
- it is in milliseconds and 20 ms
is very short time and in some image viewers I can't see how fast frames are changed. When I use 500 ms
(0.5 second) then I can see animation. BTW: it seems it can eventually get fps
(frames per seconds) instead duration
import imageio.v3 as iio
images = []
for filename in ['1.png', '2.png', '3.png']:
images.append(iio.imread(filename))
iio.imwrite('animated-gif-20ms.gif', images, duration=20)
iio.imwrite('animated-gif-500ms.gif', images, duration=500)
iio.imwrite('animated-gif-2fps.gif', images, fps=2)
Other problem can be also where you check this animation. If I put it directly in web browser (Firefox) or test with some image viewers then it displays animation only once and for duration 20ms I can see only last frame.
Documentation for Supported Formats shows that it uses pillow
to create gif
and it can get also other options imageio.plugins.pillow_legacy
If I add loop=0
then image loops in Firefox and in image viewers.
iio.imwrite(..., loop=0)