Search code examples
pythonpandasanimationplotlywide-format-data

Animate px.line line with plotly express


Learning plotly line animation and come across this question
My df:

Date 1Mo 2Mo 3Mo 6Mo 1Yr 2Yr
0 2023-02-12 4.66 4.77 4.79 4.89 4.50 4.19
1 2023-02-11 4.66 4.77 4.77 4.90 4.88 4.49
2 2023-02-10 4.64 4.69 4.72 4.88 4.88 4.79
3 2023-02-09 4.62 4.68 4.71 4.82 4.88 4.89
4 2023-02-08 4.60 4.61 4.72 4.83 4.89 4.89

How do I animate this dataframe so the frame has x = [1Mo, 2Mo, 3Mo, 6Mo, 1Yr, 2Yr], and
y = the actual value on a date, eg y=df[df['Date']=="2023-02-08"], animation_frame = df['Date']?
I tried

plot = px.line(df, x=df.columns[1:], y=df['Date'], title="Treasury Yields", animation_frame=df_treasuries_yield['Date'])

No joy :(


Solution

  • I think the problem is you cannot pass multiple columns to the animation_frame parameter. But we can get around this by converting your df from wide to long format using pd.melt – for your data, we will want to take all of the values from [1Mo, 2Mo, 3Mo, 6Mo, 1Yr, 2Yr] and put them a new column called "value" and we will have a variable column called "variable" to tell us which column the value came from.

    df_long = pd.melt(df, id_vars=['Date'], value_vars=['1Mo', '2Mo', '3Mo', '6Mo', '1Yr', '2Yr'])
    

    This will look like the following:

              Date variable  value
    0   2023-02-12      1Mo   4.66
    1   2023-02-11      1Mo   4.66
    2   2023-02-10      1Mo   4.64
    3   2023-02-09      1Mo   4.62
    4   2023-02-08      1Mo   4.60
    ...
    28  2023-02-09      2Yr   4.89
    29  2023-02-08      2Yr   4.89
    

    Now can pass the argument animation_frame='Date' to px.line:

    fig = px.line(df_long, x="variable", y="value", animation_frame="Date", title="Yields")
    

    enter image description here