1

我正在尝试使用赛璐珞构建动画热图。x & y 轴和色标是相同的,但我的代码返回下面的奇怪输出。

在此处输入图像描述

我的代码使用 seaborn、numpy、pandas 和赛璐珞,并简化如下:

from celluloid import Camera

## Set up celluloid
fig = plt.figure(figsize=(12, 9))
camera = Camera(fig)


## Loop to create figures
for item in range(len(df)):
   row = df.iloc[item]
   row = np.array(list(row))

   ## Create df from row
   shape = (8,12)
   df_row = pd.DataFrame(row.reshape(shape))

   ## Build seaborn heatmap
   ax = sns.heatmap(df_row, cmap="Greys", annot=False, vmin=0, vmax=1)
   ax.set_title(item)
   ax.xaxis.tick_top()
   for tick in ax.get_yticklabels():
      tick.set_rotation(0)
   
   ## Snap Celluloid
   camera.snap()

anim = camera.animate(interval=500)
anim.save("animation.mp4")
4

1 回答 1

1

问题是 seaborn 不断创建一个新的颜色条。ax为了解决这个问题,需要在代码开头创建一个固定的颜色条。

这是一般设置,使用celluloid's Camera。如果你忽略了,cbar_ax=cbar_ax你会看到无尽的彩条大篷车的奇怪行为。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from celluloid import Camera

fig, (ax, cbar_ax) = plt.subplots(ncols=2, figsize=(12, 9), gridspec_kw={'width_ratios': [10, 1]})
camera = Camera(fig)

for _ in range(20):
    sns.heatmap(np.random.rand(8, 12), cmap="magma", annot=False, vmin=0, vmax=1,
                ax=ax, cbar_ax=cbar_ax)
    ax.xaxis.tick_top()
    ax.tick_params(axis='y', labelrotation=0)
    camera.snap()

anim = camera.animate(interval=500)
anim.save("animation.mp4")

您的代码的关键更改是:

  • 替换fig = plt.figure(...)fig, (ax, cbar_ax) = plt.subplots(...)
  • 打电话sns.heatmapax=ax, cbar_ax=cbar_ax
于 2021-03-11T22:23:34.220 回答