2017-09-15 47 views
5

一些seaborn方法如JointPlotcreate new figures on each call。這使得不可能創建一個簡單的動畫,如matplotlib,其中對plt.cla()plt.clf()的迭代調用允許在每次不關閉/打開窗口的情況下更新圖形的內容。重繪動畫Seaborn數字

我目前看到的唯一的解決辦法是:

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) 

這工作,因爲我們正確的創建一個新之前關閉一個窗口。但當然,這遠非理想。

有沒有更好的方法?不知何故可以直接在先前生成的Figure對象上完成情節?或者有沒有辦法阻止這些方法在每次通話中產生新的數字?

回答

4

不幸的是,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() 

enter image description here

+0

我懷疑這樣的事情。我希望這會更直接,但這樣做可以很好地完成工作,所以非常感謝。 – runDOSrun

+0

從seaborn的源代碼中,你會發現它顯然沒有被寫入可能會記住動畫的情節。根據最終目標是什麼,當然可以進行一些優化;我正在考慮繼承JointGrid的方法,使其更容易被更新,並將其放在一個新的模塊中,並在需要時調用它 - 但是如果需要更頻繁地執行此類動畫,這隻會有意義。另外請記住,seaborn大多數是包裝matplotlib,這樣一個解決方案可能是複製聯合圖純粹用matplotlib做的事情。 – ImportanceOfBeingErnest