簡體   English   中英

如何對Seaborn的Lmplot進行模擬

[英]How to funcanimation seaborn's lmplot

這是這個問題的延伸

你好

我正在嘗試使用新數據更新lmplot,但由於它們具有自己的特性,因此無法找到將其連接到現有圖形/軸的方法。 到目前為止,我已經嘗試過像這樣:

%matplotlib notebook

import matplotlib.animation as animation
import numpy as np

#fig, ax = plt.subplots(1,1,figsize=(5,4))

df = get_data()
g = sns.lmplot( x='Mean', y='Variance', data=df, fit_reg=False, hue='Size', legend=False, palette=cmap)

def get_data():
    takeRandomSample(population, popSize, popVar)   
    current_elem = len(sampleStats)-1
    current_size = sampleStats[current_elem][0]
    current_mean = sampleStats[current_elem][1]
    current_var =  sampleStats[current_elem][2]

    data = {'Size' : current_size, 'Mean' : current_mean, 'Variance' : current_var}
    df = pd.DataFrame(data, index=[0])

    return df


def prep_axes(g):
    g.set(xlim=(0, 20), ylim=(0, 100), xticks=range(0,21))    

    ax = g.axes[0,0]       
    ax.axvline(x=popMean, color='#8c8ca0', ls='dashed')
    ax.axhline(y=popVar, color='#8c8ca0', ls='dashed')
    ax.set_title('Sample Statistics :{}'.format(i))
    ax.set_facecolor(backgroundColour)

def animate(i):
    df = get_data()
    g = sns.lmplot( x='Mean', y='Variance', data=df, fit_reg=False, hue='Size', legend=False, palette=cmap)
    prep_axes(g, i)


# initialize samples
sampleStats = []

plt.tight_layout()

ani = animation.FuncAnimation(g.fig, animate, frames = np.arange(1,100), interval=100)

輸出:
在此處輸入圖片說明

問題:
1.這只會產生一個靜態圖,因為我找不到更新現有g並在相同g的圖形lmsplot上重新繪圖的方法。 動畫功能正在創建新的g
2.我不得不不必要地初始化一次,以使g對象將g.fig傳遞給funcanimation,但由於第1點的原因,它也無濟於事。

我們如何使用lmplot制作動畫? 由於色相功能,我想使用它而不是常規的matplotlib。

我也嘗試直接使用facetgrid(並在g.map中傳遞lmplot),但這也無濟於事。

作為記錄,這是如何為lmplot()設置動畫,前提是您沒有任何方面而且您不關心回歸:

import seaborn as sns; sns.set(color_codes=True)
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, fit_reg=False)
fig = g.fig
ax = g.axes[0,0]
scatters = [c for c in ax.collections if isinstance(c, matplotlib.collections.PathCollection)]
txt = ax.text(0.1,0.9,'frame=0', transform=ax.transAxes)

def animate(i):
    for c in scatters:
        # do whatever do get the new data to plot
        x = np.random.random(size=(50,1))*50
        y = np.random.random(size=(50,1))*10
        xy = np.hstack([x,y])
        # update PathCollection offsets
        c.set_offsets(xy)
    txt.set_text('frame={:d}'.format(i))
    return scatters+[txt]

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=10, blit=True)

在此處輸入圖片說明

但是,在這種情況下,通過完全不使用lmplot,您可以以一種更加直接的方式獲得幾乎完全相同的結果:

import seaborn as sns; sns.set(color_codes=True)
tips = sns.load_dataset("tips")

fig, ax = plt.subplots()
scatters = []
for g,d in tips.groupby('smoker'):
    s = ax.scatter(x="total_bill", y="tip", data=tips, label=g)
    scatters.append(s)
ax.legend(bbox_to_anchor=(1.,1.), loc=1)
txt = ax.text(0.1,0.9,'frame=0', transform=ax.transAxes)

def animate(i):
    for c in scatters:
        x = np.random.random(size=(50,1))*50
        y = np.random.random(size=(50,1))*10
        xy = np.hstack([x,y])
        c.set_offsets(xy)
    txt.set_text('frame={:d}'.format(i))
    return scatters+[txt]

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=10, blit=True)

在此處輸入圖片說明

從上面的代碼中,很容易將新值附加到先前的數據中,而不是替換所有要點:

import seaborn as sns; sns.set(color_codes=True)
tips = sns.load_dataset("tips")

fig, ax = plt.subplots()
scatters = []
for g,d in tips.groupby('smoker'):
    s = ax.scatter([], [], label=g)
    scatters.append(s)
ax.legend(bbox_to_anchor=(1.,1.), loc=1)
txt = ax.text(0.1,0.9,'frame=0', transform=ax.transAxes)
ax.set_xlim((0,60))
ax.set_ylim((0,15))

def animate(i, df, x, y, hue):
    new_data = df.sample(20) # get new data here
    for c,(groupname,subgroup) in zip(scatters,new_data.groupby(hue)):
        xy = c.get_offsets()
        xy = np.append(xy,subgroup[[x,y]].values, axis=0)
        c.set_offsets(xy)
    txt.set_text('frame={:d}'.format(i))
    return scatters+[txt]

ani = matplotlib.animation.FuncAnimation(fig, animate, fargs=(tips, "total_bill", "tip", 'smoker'), frames=10, blit=True)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM