Redrawing marine figures for animation

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

The only solution that I see now 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 before creating a new one. But, of course, this is far from ideal.

Is there a better way? Can the plot be somehow made directly on the previously generated Figure object? Or is there a way to prevent these methods from appearing on every call?

+5
source share
1 answer

Unfortunately, sns.jointplot creates a shape by itself. To revitalize the joint plan, one could reuse this created figure instead of re-creating a new one in each interaction.

jointplot internally creates a JointGrid , so it makes sense to directly use it and build individual axes and margins. At each stage of the animation, it would be possible to update the data, clear the axes and adjust them in the same way as when creating the grid. Unfortunately, this last step involves many lines of code.

The final code might look like this:

 import matplotlib.pyplot as plt import matplotlib.animation import seaborn as sns import numpy as np def get_data(i=0): x,y = np.random.normal(loc=i,scale=3,size=(2, 260)) return x,y x,y = get_data() g = sns.JointGrid(x=x, y=y, size=4) lim = (-10,10) def prep_axes(g, xlim, ylim): g.ax_joint.clear() g.ax_joint.set_xlim(xlim) g.ax_joint.set_ylim(ylim) g.ax_marg_x.clear() g.ax_marg_x.set_xlim(xlim) g.ax_marg_y.clear() g.ax_marg_y.set_ylim(ylim) plt.setp(g.ax_marg_x.get_xticklabels(), visible=False) plt.setp(g.ax_marg_y.get_yticklabels(), visible=False) plt.setp(g.ax_marg_x.yaxis.get_majorticklines(), visible=False) plt.setp(g.ax_marg_x.yaxis.get_minorticklines(), visible=False) plt.setp(g.ax_marg_y.xaxis.get_majorticklines(), visible=False) plt.setp(g.ax_marg_y.xaxis.get_minorticklines(), visible=False) plt.setp(g.ax_marg_x.get_yticklabels(), visible=False) plt.setp(g.ax_marg_y.get_xticklabels(), visible=False) def animate(i): gx, gy = get_data(i) prep_axes(g, lim, lim) g.plot_joint(sns.kdeplot, cmap="Purples_d") g.plot_marginals(sns.kdeplot, color="m", shade=True) frames=np.sin(np.linspace(0,2*np.pi,17))*5 ani = matplotlib.animation.FuncAnimation(g.fig, animate, frames=frames, repeat=True) plt.show() 

enter image description here

+4
source

Source: https://habr.com/ru/post/1271835/


All Articles