如何使用 plotly express 创建热图动画? [英] How to create a heatmap animation with plotly express?
问题描述
我有一个方阵列表 M[t],其中 t 的范围从 0 到 N,我希望使用 plotly.express 创建一个动画热图.每行/列中的条目对应一个列表,a=['a1','a2',...'aN']
I have a list of square matrices, M[t], where t ranges from 0 to N and I wish to create an animated heatplot using plotly.express. The entries in each row/column correspond to a list, a=['a1','a2',...'aN']
关于动画的情节文档相当稀少,只关注散点图和条形图
The plotly documentation on animation is fairly sparse and focuses on just scatterplots and barplots
https://plotly.com/python/animations/
一个与我类似的问题已发布在
A question similar to mine was posted at
但是,用户在 Jupyter notebook 中工作.我只是在 Mac (OS 10.15.4) 上使用带有 IDLE 的 Python 3.7
However, the user is working in a Jupyter notebook. I'm simply using Python 3.7 with IDLE on a Mac (OS 10.15.4)
我知道如何使用 matplotlib 或 seaborn 创建基本动画,但我喜欢 plotly express 内置的开始/停止按钮.这是我使用的一种方法,但我确信使用 matplotlib.animation 有更有效的方法:
I know how to create a basic animation using matplotlib or seaborn, but I like the built-in start/stop buttons that come with plotly express. Here's one approach I use, but I'm sure there are more efficient ways using 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)
推荐答案
这对您有用吗?
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()
UPDATE 如果您需要添加暂停
按钮
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()
这篇关于如何使用 plotly express 创建热图动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!