获取某个轴 matplotlib 的所有艺术家?

J.D*_*Doe 3 python animation matplotlib

我正在尝试在 mpl 中对绘图进行动画处理,并且我决定最明智的方法是使用 Gridspec 动态添加多个轴。我提供了一些我希望 Gridspec 在我的画布上制作轴的列和行,然后我可以用艺术家填充这些轴。

由于轴的数量是任意的,因此艺术家的数量也是任意的,我认为最好像这样访问艺术家:

import matplotlib.pyplot as plt

fig = plt.figure(constrained_layout=False, figsize=(8,8), facecolor=bg_colour)
gs = fig.add_gridspec(nrows=nrows, ncols=ncols, hspace=0.1, wspace=0.1)

for i in range(nrows):
    for j in range(ncols):
        ax = plt.subplot(gs[i,j])

print(fig.axes[0].artists)
Run Code Online (Sandbox Code Playgroud)

所以我的想法是,我可以动态创建所有轴,然后我还可以通过fig.axes使用适当的索引进行切片来动态地将艺术家添加到这些轴。一旦我选择了我的轴我就可以做

fig.axes[0].plot([],[])
Run Code Online (Sandbox Code Playgroud)

将一个空艺术家添加到右轴,然后我可以使用代码中的更新函数为其设置动画。

问题是,无论我如何设置图形、轴和艺术家的创建,列表fig.axes[index].artists始终为空。我不明白如何发出命令来绘制我的轴,然后不让艺术家出现在所有艺术家的列表中。是.artists我需要使用的所有艺术家的容器吗?我要找的东西是否存放在其他地方?难道mpl实际上一开始就不允许这种事情发生吗?

完整代码

import numpy as np
import itertools
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.ticker import AutoMinorLocator, MaxNLocator




def circle_points_x(period):

    t = np.linspace(0,2*np.pi,500)
    x = np.cos(period*t +np.pi/2)

    return x

def circle_points_y(period):

    t = np.linspace(0,2*np.pi,500)
    y = np.sin(period*t +np.pi/2)

    return y


# true distribution
ncols,nrows = (5,5)

bg_colour = np.array((84, 153, 215))/256
bg_colour = np.append(bg_colour,0.5)

fig = plt.figure(constrained_layout=False, figsize=(8,8), facecolor=bg_colour)

gs = fig.add_gridspec(nrows=nrows, ncols=ncols, hspace=0.1, wspace=0.1)


for i in range(nrows):
    for j in range(ncols):
        ax = plt.subplot(gs[i,j])
        ax.axis('off')


def init():

    for i in range(nrows):
        for j in range(ncols):
            x = circle_points_x(j+1)
            y = circle_points_y(i+1)

            fig.axes[i*nrows +j].plot(x,y,lw=0.5,aa=True)
            fig.axes[i*nrows +j].scatter([x[0]],[y[0]])


    print(fig.axes[0].artists)

    return list(itertools.chain(*[i.artists for i in fig.axes]))


def update(frame):

    for i in range(nrows):
        for j in range(ncols):
            # fig.axes[i*nrows +j].artists[0] # TURN THIS ON TO SEE THE ERROR
            pass
    return list(itertools.chain(*[i.artists for i in fig.axes]))




ani = FuncAnimation(fig, update, frames=range(1,8),repeat=False,init_func=init, blit=True,interval=40)
# ani.save('histogram.gif', dpi=300 ,writer="ffmpeg")
plt.show()
Run Code Online (Sandbox Code Playgroud)

Dav*_*_sd 8

也许您正在寻找的是ax.get_children(),但是它会返回所有内容(线条、线条集合、脊柱、图例可能...),因此您必须以某种方式过滤结果。

如果您事先知道要绘制的数据类型,这里有几个 Matplotlib 分隔艺术家的位置。

  • ax.lines存储用 创建的行ax.plot
  • ax.collectionsax.add_collection存储使用, ax.plot_surface, ax.contour, ax.contourf, ...创建的集合(线集合、多边形集合)
  • ax.images存储使用 创作的艺术家ax.imshow
  • ax.patches包含使用ax.bar, ax.fill, ....创作的艺术家
  • ax.tables包含使用 创作的艺术家ax.table