如何使用Plotly Express创建热力图动画?

6
我有一个方阵列表M[t],其中t的范围从0到N,我希望使用plotly.express创建一个动画热图。每行/列中的条目对应于一个列表a=['a1','a2',... 'aN']。 plotly关于动画的文档相当稀少,主要集中在散点图和条形图上。

https://plotly.com/python/animations/

有一个类似于我的问题发布在

如何在Plotly中为热图添加动画

但是,该用户正在使用Jupyter笔记本。我只是在Mac(OS 10.15.4)上使用Python 3.7和IDLE。

我知道如何使用matplotlib或seaborn创建基本的动画,但我喜欢plotly express附带的内置开始/停止按钮。这是我使用的一种方法,但我肯定有更有效的方法可以使用matplotlib.animation:

import numpy as np
import matplotlib.pyplot as plt
#50 matrices, each of size 4-by-4.
N = 50
M = np.random.random((50, 4,4))

#Desired labels for heatmap--not sure where to put.
labels=['a','b','c','d']

fig, ax = plt.subplots()

for t in range(50):
    ax.cla()
    ax.imshow(M[t])
    ax.set_title("frame {}".format(t))
    plt.pause(0.1)

你介意提供一个 mcve 吗? - rpanai
我刚刚编辑了一下,加入了一个10x10大小的50个矩阵的例子。 - fishbacp
1个回答

7

这对你有效吗?

import numpy as np
import plotly.graph_objs as go

N = 50
M = np.random.random((N, 10, 10))

fig = go.Figure(
    data=[go.Heatmap(z=M[0])],
    layout=go.Layout(
        title="Frame 0",
        updatemenus=[dict(
            type="buttons",
            buttons=[dict(label="Play",
                          method="animate",
                          args=[None])])]
    ),
    frames=[go.Frame(data=[go.Heatmap(z=M[i])],
                     layout=go.Layout(title_text=f"Frame {i}")) 
            for i in range(1, N)]
)

fig.show()

更新:如果您需要添加一个暂停按钮

fig = go.Figure(
    data=[go.Heatmap(z=M[0])],
    layout=go.Layout(
        title="Frame 0",
        title_x=0.5,
        updatemenus=[dict(
            type="buttons",
            buttons=[dict(label="Play",
                          method="animate",
                          args=[None]),
                    dict(label="Pause",
                         method="animate",
                         args=[None,
                               {"frame": {"duration": 0, "redraw": False},
                                "mode": "immediate",
                                "transition": {"duration": 0}}],
                         )])]
    ),
    frames=[go.Frame(data=[go.Heatmap(z=M[i])],
                     layout=go.Layout(title_text=f"Frame {i}")) 
            for i in range(1, N)]
)

fig.show()

1
谢谢!这非常有帮助。 - Sujay Phadke
1
嗨rpanai,如何添加滑块以选择每个帧?我已经寻找了很长时间。您介意更新您的代码以添加滑块吗?谢谢。 - roudan
嗨@roudan,你看过这个了吗?如果你还是做不来,请告诉我。 - rpanai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接