繁体   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