Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Matplotlib animated violinplot?

I am trying to animate a violinplot, so I have started off with something I think should be very basic, but it is not working. I think the problem is that violinplot doesn't accept set_data, but I don't otherwise know how to pass the changing data to violinplot. For this example I would like a plot where the mean slowly shifts to higher values. If I am barking up the wrong tree, please advise on a code which does work to animate violinplot.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation


fig, ax = plt.subplots()
data = np.random.rand(100)

def animate(i):
    v.set_data(data+i)  # update the data
    return v

v = ax.violinplot([])
ax.set_ylim(0,200)

v_ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), 
                              interval=50, blit=True)
like image 989
J. K. Avatar asked Apr 21 '17 21:04

J. K.


1 Answers

Indeed, there is no set_data method for the violinplot. The reason is probably, that there is a lot of calculations going on in the background when creating such a plot and it consists of a lot of different elements, which are hard to update.

The easiest option would be to simply redraw the violin plot and not use blitting.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation


fig, ax = plt.subplots()
data = np.random.normal(loc=25, scale=20, size=100)

def animate(i, data):
    ax.clear()
    ax.set_xlim(0,2)
    ax.set_ylim(0,200)
    data[:20] = np.random.normal(loc=25+i, scale=20, size=20)
    np.random.shuffle(data)
    ax.violinplot(data)

animate(0)

v_ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), 
                              fargs=(data,), interval=50, blit=False)

plt.show()

enter image description here

like image 179
ImportanceOfBeingErnest Avatar answered Nov 15 '22 00:11

ImportanceOfBeingErnest