带有轴和缺少绘图的赛璐珞动画热图问题

2024-09-28 22:04:09 发布

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

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

enter image description here

我的代码使用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")

Tags: 代码infromdfforfigseabornax
1条回答
网友
1楼 · 发布于 2024-09-28 22:04:09

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

下面是使用celluloidCamera的一般设置。如果你忽略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, (ax, cbar_ax) = plt.subplots(...)替换fig = plt.figure(...)
  • ax=ax, cbar_ax=cbar_ax调用sns.heatmap

相关问题 更多 >