Search code examples
pythonpandasplotlyplotly-express

How to pipe plotly line plot to pandas dataframe?


How can we use .pipe() to get plotly express line plot?

Code

import numpy as np
import pandas as pd
import seaborn as sns

import plotly.express as px

df = pd.DataFrame(data={'count':np.random.randint(1,20,10)},
                  index=pd.date_range('2020-01-01','2020-01-10')
                 )

Line plot (this works)

df1 = df.resample('2D').sum()
px.line(df1,x=df1.index,y='count')

Using pipe

Here creating df1 is un-necessary. How can we use pipe?

My attempt

df.resample('2D').sum().pipe(px.line,x=lambda x: x.index,y='count')
# this does not work, gives empty plot

How to get the correct image?


Solution

  • You are close:

    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    import plotly.express as px
    
    df = pd.DataFrame(data={'count':np.random.randint(1,20,10)},
                      index=pd.date_range('2020-01-01','2020-01-10')
                     )
    
    # line plot with pipe
    df.resample('2D').sum().pipe(lambda ts:
                                 px.line(ts, x=ts.index,y='count'))
    

    Output: enter image description here