I'm trying to animate multiple tracks with Python plotly.
The code is:

import pandas as pd
import plotly.express as px
df = pd.read_csv("orbite.csv")
fig=px.scatter(df,x="X1",y="Y1",animation_frame="time",range_x=[-6,1],range_y=[-5,2])\

fig.add_scatter(df,x="X2",y="Y2",animation_frame="time",range_x=[-6,1],range_y=[-5,2])

fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 20
fig.update_layout(transition = {"duration": 20})
fig.show()

以下是数据文件:

      time         X1         Y1        X2         Y2
0        1  -0.001000   0.000000  0.000000  10.000000

1        2  -0.001000   0.000000 -0.035000   9.940000

2        3  -0.000951   0.000049 -0.070000   9.890000

3        4  -0.000853   0.000148 -0.105000   9.830000

4        5  -0.000707   0.000297 -0.140000   9.780000

该程序只有一个动画运行良好,但如果我加上fig.add_scatter(),我会得到错误:

The 'alignmentgroup' property is a string and must be specified as:
  - A string
  - A number that will be converted to a string

怎么了?

推荐答案

add_scatter不使用与px.散布相同的功能(例如,请参见https://stackoverflow.com/a/67529369/9501624),因此不能用于"组合动画".

据我所知,唯一的方法就是在graph_objects and frames的基础上"重建"新图形中的帧(例如,参见Animating & overlaying multiple plots with plotly):

enter image description here

import pandas as pd
import plotly.express as px
from plotly import graph_objects as go

data = {
    "time": [1, 2, 3, 4, 5],
    "X1": [0.5, 0.4, 0.3, 0.2, 0.1],
    "Y1": [0.5, 0.4, 0.3, 0.2, 0.1],
    "X2": [-0.5, -0.4, -0.3, -0.2, -0.1],
    "Y2": [-0.5, -0.4, -0.3, -0.2, -0.1],
}
df = pd.DataFrame(data)
fig1 = px.scatter(df, x="X1", y="Y1", animation_frame="time")
fig2 = px.scatter(df, x="X2", y="Y2", animation_frame="time")

# build frames to be animated from two source figures.
frames = [
    go.Frame(data=f.data + fig1.frames[i].data, name=f.name)
    for i, f in enumerate(fig2.frames)
]

combined_fig = go.Figure(data=frames[0].data, frames=frames, layout=fig1.layout)
combined_fig.show()

Python相关问答推荐

如何将 map 数组组合到pyspark中每列的单个 map 中

按日期和组增量计算总价值

将词典写入Excel

Snap 7- read_Area用于类似地址的变量

绘制系列时如何反转轴?

pyautogui.locateOnScreen在Linux上的工作方式有所不同

通过仅导入pandas来在for循环中进行多情节

如何从FDaGrid实例中删除某些函数?

TARete错误:类型对象任务没有属性模型'

不理解Value错误:在Python中使用迭代对象设置时必须具有相等的len键和值

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

Pandas计数符合某些条件的特定列的数量

Pandas DataFrame中行之间的差异

形状弃用警告与组合多边形和多边形如何解决

旋转多边形而不改变内部空间关系

如何在PySide/Qt QColumbnView中删除列

Matplotlib中的字体权重

在pandas/python中计数嵌套类别

如何创建引用列表并分配值的Systemrame列

如何在Python Pandas中填充外部连接后的列中填充DDL值