如何导出/保存用plotly制作的动态气泡图?(例如,按照下面的链接制作的那个)我希望将其保存为更高分辨率的gif或其他格式。提前感谢您。
https://www.kaggle.com/aashita/guide-to-animated-bubble-charts-using-plotly
https://www.kaggle.com/aashita/guide-to-animated-bubble-charts-using-plotly
gifmaker
并将动画的每个步骤保存为单独的图片,然后将它们组合成gif。查看源文件。有关如何创建动画的更多说明,请参见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()
在已经提供的答案基础上继续构建。这将从一个带有帧(动画)的 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,
)
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)
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)