如何在情节中为直线制作动画?

How to animate a straight in plotly?

我想可视化将直线拟合到二维数据集的过程。 对于每个纪元,我都有直线起点和终点的 x 和 y 坐标。下面是带有一条线 (matplotlib) 的数据集的示例图像。

我看到 plotly 提供了一个动画线条的选项。

上面的图是用类似这样的代码创建的:

# this should animate my line
fig_data = px.line(df, x="xxx", y="yyy", animation_frame="epoch", animation_group="name", title="fitted line")

# responsible for the red scatter plot points:
fig_data.add_traces(
    go.Scatter(
        x=xxx, 
        y=yyy, mode='markers', name='House in Dataset')
)

数据框看起来像这样:

epoch       xxx                                       yyy      name
0       0  [0.5, 4]   [1.4451884285714285, 4.730202428571428]  example
1       1  [0.5, 4]  [1.3944818842653062, 4.4811159469795925]  example
2       2  [0.5, 4]   [1.3475661354539474, 4.251154573663417]  example
3       3  [0.5, 4]    [1.3041510122346094, 4.03885377143571]  example

所以应该在纪元 0 中显示的行从 (0.5,1.44) 开始到 (4,4.73)。 但是,不会呈现任何线条。我应该改变什么?

我认为问题出在 dfxxxyyy 的格式,因为它们现在是嵌套数组,似乎没有被正确引用通过 px.line.

您可以使用 pd.Series.explode 来“展平”此数据框(示例 ) and then use that as the input to px.line. See here 以获得有关熊猫爆炸的更多信息。

使用 xdf=df.set_index('epoch').apply(pd.Series.explode).reset_index() 将产生:

epoch   xxx      yyy       name
0   0   0.5 1.445188    example
1   0   4   4.730202    example
2   1   0.5 1.394482    example
3   1   4   4.481116    example
4   2   0.5 1.347566    example
5   2   4   4.251155    example
6   3   0.5 1.304151    example
7   3   4   4.038854    example

带注释的完整示例:

import plotly.express as px
import pandas as pd

data = {'epoch': [0,1,2,3], 
        'xxx': [[0.5, 4], [0.5, 4], [0.5, 4], [0.5, 4]],
        'yyy': [[1.4451884285714285, 4.7302024285714280], 
                [1.3944818842653062, 4.4811159469795925], 
                [1.3475661354539474, 4.2511545736634170], 
                [1.3041510122346094, 4.0388537714357100]],
       'name':['example','example','example','example']}  
df = pd.DataFrame.from_dict(data)

# now exploding `df`
xdf=df.set_index('epoch').apply(pd.Series.explode).reset_index()

# now plotting using xdf as dataframe input
px.line(xdf, x="xxx", y="yyy", animation_frame="epoch", color="name", title="fitted line")

注意:似乎缺少散点图的原始数据,但我认为这不是问题所在。