【发布时间】:2020-09-29 15:34:32
【问题描述】:
我正在使用以下代码使用 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 个子图添加描述。它应该显示图像在哪一步,即“step = 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),但是现有图像被绘制了..
有没有人可以解决这个问题?
编辑:
目前不干净,hacky 的解决方案: 等待创建最后一行的中间图像的轴并将其用于绘制文本。 在 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)
...
【问题讨论】:
标签: python matplotlib animation title subplot