python matplotlib在动画的多个子地块上共享xlabel描述/标题

2024-05-13 02:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用下面的代码用matplotlib生成一个动画,用于可视化我的实验

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation, PillowWriter

plt.rcParams['animation.html'] = 'jshtml'

def make_grid(X, description=None, labels=None, title_fmt="label: {}", cmap='gray', ncols=3, colors=None):
    L = len(X)
    nrows = -(-L // ncols)
    frame_plot = []
    for i in range(L):
        plt.subplot(nrows, ncols, i + 1)
        im = plt.imshow(X[i].squeeze(), cmap=cmap, interpolation='none')
        if labels is not None:
            color = 'k' if colors is None else colors[i]
            plt.title(title_fmt.format(labels[i]), color=color)
        plt.xticks([])
        plt.yticks([])
        frame_plot.append(im)
    return frame_plot


def animate_step(X):
    return X ** 2

n_splots = 6
X = np.random.random((n_splots,32,32,3))

Y = X
X_t = []

for i in range(10):
    Y = animate_step(Y)
    X_t.append((Y, i))

frames = []
for X, step in X_t:
    frame = make_grid(X,
                    description="step={}".format(step),
                    labels=range(n_splots),
                    title_fmt="target: {}")
    frames.append(frame)

anim = ArtistAnimation(plt.gcf(), frames,
                        interval=300, repeat_delay=8000, blit=True)
plt.close()                               
anim.save("test.gif", writer=PillowWriter())
anim

结果如下所示: https://i.stack.imgur.com/OaOsf.gif

到目前为止,它还可以正常工作,但是我很难让共享的xlabel为动画中的所有6个子情节添加描述。它应该显示图像所处的步骤,即“步骤=5”。 由于它是一个动画,我不能使用xlabel或set_title(因为它在整个动画中是恒定的),而必须自己绘制文本。 我试过一些类似于

def make_grid(X, description=None, labels=None, title_fmt="label: {}", cmap='gray', ncols=3, colors=None):
    L = len(X)
    nrows = -(-L // ncols)
    frame_plot = []
    desc = plt.text(0.5, .04, description,
                    size=plt.rcparams["axes.titlesize"],
                    ha="center",
                    transform=plt.gca().transAxes
                    )
    frame_plot.append(desc)
...

当然,这不会起作用,因为尚未创建轴。我尝试使用另一个子图(nrows,1,nrows)的轴,但是现有图像被绘制出来了

有人能解决这个问题吗

编辑:

目前,不干净、有问题的解决方案: 等待创建最后一行中间图像的轴,并使用该轴打印文本。 在for循环中:

...
        if i == int((nrows - 0.5) * ncols):
            title = ax.text(0.25, -.3, description,
                            size=plt.rcParams["axes.titlesize"],
                            # ha="center",
                            transform=ax.transAxes
                            )
            frame_plot.append(title)
...

Tags: nonelabelsplottitlestep动画pltdescription
1条回答
网友
1楼 · 发布于 2024-05-13 02:27:40

对我来说,用FuncAnimation而不是ArtistAnimation来解决您的问题更容易,即使您已经可以访问要显示动画的完整数据列表(有关这两个函数之间差异的讨论,请参见this thread

this FuncAnimation example的启发,我编写了下面的代码来满足您的需要(使用与ArtistAnimation相同的代码,正确的参数列表不起作用)

其主要思想是在开始时初始化要设置动画的所有元素,并在动画帧中更新它们。这可以对负责显示当前步骤的文本对象(step_txt = fig.text(...))和来自ax.imshow的图像执行。然后,您可以更新任何您希望使用此配方设置动画的对象

请注意,如果您希望文本是x_label或任何您选择显示的文本,则该技术是有效的。请参阅代码中的注释行

#!/Users/seydoux/anaconda3/envs/jupyter/bin/python
import numpy as np
import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation, PillowWriter

# parameters
n_frames = 10
n_splots = 6
n_cols = 3
n_rows = n_splots // n_cols


def update_data(x):
    return x ** 2


# create all snapshots
snapshots = [np.random.rand(n_splots, 32, 32, 3)]
for _ in range(n_frames):
    snapshots.append(update_data(snapshots[-1]))

# initialize figure and static elements
fig, axes = plt.subplots(2, 3)
axes = axes.ravel()  # so we can access all axes with a single index
for i, ax in enumerate(axes):
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_title("target: {}".format(i))

# initialize elements to be animated
step_txt = fig.text(0.5, 0.95, "step: 0", ha="center", weight="bold")
# step_txt = axes[4].set_xlabel("step: 0")  # also works with x_label
imgs = list()
for a, s in zip(axes, snapshots[0]):
    imgs.append(a.imshow(s, interpolation="none", cmap="gray"))


# animation function
def animate(i):

    # update images
    for img, s in zip(imgs, snapshots[i]):
        img.set_data(s)

    # update text
    step_txt.set_text("step: {}".format(i))

    # etc


anim = FuncAnimation(fig, animate, frames=n_frames, interval=300)
anim.save("test.gif", writer=PillowWriter())

以下是我从上述代码中获得的输出:

animated with step display

相关问题 更多 >