如何使用Plotly导出/保存制作的动态气泡图表?

7

我的回答解决了您的问题吗?如果是,请接受并点赞。 :) 祝好 - Mike_H
4个回答

8
在Plotly中无法直接实现此功能。请使用gifmaker并将动画的每个步骤保存为单独的图片,然后将它们组合成gif。查看源文件。有关如何创建动画的更多说明,请参见Plotly这里提供的说明。
基本方法是将此逻辑集成到您的Plotly代码的动画过程中:
 import ImageSequence
 import Image
 import gifmaker
 sequence = []

 im = Image.open(....)

 # im is your original image
 frames = [frame.copy() for frame in ImageSequence.Iterator(im)]

 # write GIF animation
 fp = open("out.gif", "wb")
 gifmaker.makedelta(fp, frames)
 fp.close()

如果您能提供实际的代码,就可以更详细地回答您的问题。 :)

5

在已经提供的答案基础上继续构建。这将从一个带有帧(动画)的 plotly 图形中生成一个动态 GIF。

  • 首先生成一些测试数据
  • 使用 plotly express 生成一个动画图形
  • 为每个plotly图形中的帧创建一个图像
  • 最后从图像列表生成动态 GIF
import plotly.express as px
import pandas as pd
import numpy as np
import io
import PIL

r = np.random.RandomState(42)

# sample data
df = pd.DataFrame(
    {
        "step": np.repeat(np.arange(0, 8), 10),
        "x": np.tile(np.linspace(0, 9, 10), 8),
        "y": r.uniform(0, 5, 80),
    }
)

# smaple plotly animated figure
fig = px.bar(df, x="x", y="y", animation_frame="step")

# generate images for each step in animation
frames = []
for s, fr in enumerate(fig.frames):
    # set main traces to appropriate traces within plotly frame
    fig.update(data=fr.data)
    # move slider to correct place
    fig.layout.sliders[0].update(active=s)
    # generate image of current state
    frames.append(PIL.Image.open(io.BytesIO(fig.to_image(format="png"))))
    
# create animated GIF
frames[0].save(
        "test.gif",
        save_all=True,
        append_images=frames[1:],
        optimize=True,
        duration=500,
        loop=0,
    )

enter image description here


干得好!之前从未见过这样的东西。非常有用! - vestland

5
另一种可能性是使用gif库,该库与matplolib、altair和plotly兼容,并且非常直观。在这种情况下,您将不使用plotly动画。相反,您定义一个返回plotly fig的函数,并构造一个figs列表作为参数传递给gif。
您的代码应该类似于这样:
import random
import plotly.graph_objects as go
import pandas as pd
import gif

# Pandas DataFrame with random data
df = pd.DataFrame({
    't': list(range(10)) * 10,
    'x': [random.randint(0, 100) for _ in range(100)],
    'y': [random.randint(0, 100) for _ in range(100)]
})

# Gif function definition
@gif.frame
def plot(i):
    d = df[df['t'] == i]
    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=d["x"],
        y=d["y"],
        mode="markers"
    ))
    fig.update_layout(width=500, height=300)
    return fig

# Construct list of frames
frames = []
for i in range(10):
    frame = plot(i)
    frames.append(frame)

# Save gif from frames with a specific duration for each frame in ms
gif.save(frames, 'example.gif', duration=100)

1
只是想分享一下我找到的解决方案,我认为根据你的情况可能会更容易一些。这个解决方案对我有效,并且只使用了Pillow外部库。
import PIL.Image
import io
import plotly.express as px

# Generate your animated plot.
plot = px.bar(data_frame=your_data, x=your_x, y=your_y, animation_frame=your_af)

# Save each plot frame to a list that is used to generate the .gif file. 
frames = []
for slider_pos, frame in enumerate(plot.frames):
    plot.update(data=frame.data)
    plot.layout.sliders[0].update(active=slider_pos)
    frames.append(PIL.Image.open(io.BytesIO(plot.to_image(format="png"))))
    
# Create the gif file.
frames[0].save("out_dir",
               save_all=True,
               append_images=frames[1:],
               optimize=True,
               duration=1000,
               loop=0)

gif的循环状态可以通过循环参数进行控制,其中0表示它将无限重复。持续时间参数表示帧之间的毫秒数。

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