不幸的是,sns.jointplot
自己創建了一個數字。爲了使jointplot動畫,可以重新使用這個創建的圖形,而不是在每個交互中重新創建一個新圖形。
jointplot
內部創建一個JointGrid
,所以直接使用它並單獨繪製關節軸和邊緣圖是有意義的。在動畫的每一步中,人們都會更新數據,清除軸並將其設置爲與創建網格時相同。不幸的是,這最後一步涉及很多代碼行。然後
最後的代碼可能看起來像:
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):
g.x, g.y = 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()
我懷疑這樣的事情。我希望這會更直接,但這樣做可以很好地完成工作,所以非常感謝。 – runDOSrun
從seaborn的源代碼中,你會發現它顯然沒有被寫入可能會記住動畫的情節。根據最終目標是什麼,當然可以進行一些優化;我正在考慮繼承JointGrid的方法,使其更容易被更新,並將其放在一個新的模塊中,並在需要時調用它 - 但是如果需要更頻繁地執行此類動畫,這隻會有意義。另外請記住,seaborn大多數是包裝matplotlib,這樣一個解決方案可能是複製聯合圖純粹用matplotlib做的事情。 – ImportanceOfBeingErnest