使用blit技术实现Seaborn绘图动画时,如何获取需返回的Artist?
Seaborn结合Matplotlib Blit实现动画的正确方法
问题根源
直接返回ax.get_children()会报错,是因为该方法返回的列表包含大量非可重绘的元素(如隐藏刻度、轴框架组件等),其中部分元素为NoneType,不具备blit所需的_get_view方法。
解决思路
不要返回轴的所有子元素,而是提取Seaborn绘图生成的实际可重绘Artist对象:
- 二维KDE图(联合轴)生成的是
PathCollection,存储在轴的collections属性中 - 一维KDE图(边际轴)生成的是
Line2D对象,存储在轴的lines属性中
修改后的完整代码
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import seaborn as sns import random g = sns.JointGrid() x,y = [0], [0] x_lim = (-2,2) y_lim = (-2,2) def prep_axis(g, x_lim, y_lim): g.ax_joint.clear() g.ax_joint.set_xlim(x_lim) g.ax_joint.set_ylim(y_lim) g.ax_marg_x.clear() g.ax_marg_x.set_xlim(x_lim) g.ax_marg_y.clear() g.ax_marg_y.set_ylim(y_lim) 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(frame): global g, x_lim, y_lim prep_axis(g, x_lim, y_lim) x.append(random.uniform(-1, 1)) y.append(random.uniform(-1, 1)) # 绘制KDE图 sns.kdeplot(x=x, y=y, ax=g.ax_joint) sns.kdeplot(x=x, linewidth=2, ax=g.ax_marg_x) sns.kdeplot(y=y, linewidth=2, ax=g.ax_marg_y) # 提取需要重绘的Artist对象 artists = [] artists.extend(g.ax_joint.collections) artists.extend(g.ax_marg_x.lines) artists.extend(g.ax_marg_y.lines) return artists anim = FuncAnimation( g.figure, animate, interval = 50, blit = True, # 开启blit repeat = True ) plt.show()
关键说明
- 每次动画帧先清除轴内容,再重新绘制KDE图
- 只提取绘图生成的
collections和lines,这些是真正需要重绘的视觉元素 - 开启
blit=True即可实现高效动画,避免全图重绘
内容的提问来源于stack exchange,提问作者Eledwin
相关产品推荐
相关产品推荐

