Redrawing Seaborn Figures for Animations

Viewed 9110

Some seaborn methods like JointPlot create new figures on each call. This makes it impossible to create a simple animation like in matplotlib where iterative calls to plt.cla() or plt.clf() allow to update the contents of a figure without closing/opening the window each time.

The only solution I currently see is:

for t in range(iterations):
    # .. update your data ..

    if 'jp' in locals():
        plt.close(jp.fig)

    jp = sns.jointplot(x=data[0], y=data[1])
    plt.pause(0.01)

This works because we close the previous window right before creating a new one. But of course, this is far from ideal.

Is there a better way? Can the plot somehow be done directly on a previously generated Figure object? Or is there a way to prevent these methods to generate new figures on each call?

2 Answers

using the celluloid package (https://github.com/jwkvam/celluloid) I was able to animate seaborn plots without much hassle:

import numpy as np
from celluloid import Camera
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fig = plt.figure()
camera = Camera(fig)

# animation draws one data point at a time
for i in range(0, data.shape[0]):
    plot = sns.scatterplot(x=data.x[:i], y=data.y[:i])
    camera.snap()

anim = camera.animate(blit=False)
anim.save('animation.mp4')

I'm sure similar code could be written for jointplots

Related