如何在Plotly中制作一条直线动画?

3
我想可视化拟合2D数据集的直线拟合过程。对于每个时代,我都有直线起点和终点的x和y坐标。下面是一个带有直线的数据集示例图像(使用matplotlib)。

enter image description here

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

enter image description here

上面的图表是使用类似于以下代码创建的:
# 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)。但是,没有呈现任何线条。我应该改变什么?


datapoints_xdatapoint_y是从哪里来的? - jayveesea
我的错。现在已经修复了。 - egjada
1个回答

2
我认为问题出在 `df` 中的 `xxx` 和 `yyy` 的格式上,它们现在是嵌套数组,似乎没有被 px.line 正确引用。

您可以使用 pd.Series.explode 来“展开”这个数据框(示例 here),然后将其作为输入传递给 px.line。请参见 here 以获取有关 pandaa 的 explode 的更多信息。

使用 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")


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

enter image description here


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