Search code examples
pythonpandasmatplotlibplotlyplotly-express

Matplotlib like graphs with plotly express


Following is my Pandas dataframe, its very easy creating a line plot for all the items with matplotlib. I just write

df.plot()

And it create a separate line for all the items, But I want to create same line plots with plotly express, But I am not able to do it, may be because I have date columns

df;
dataDate 2019-10-01 2019-10-02  2019-10-01  2019-10-01  2019-10-02 
name                        
item1      0.24      0.12       0.19        0.20        0.12    
item2      0.26      0.25       0.17        0.17        0.13    
item3      0.22      0.24       0.18        0.17        0.16    
item4      0.72      0.22       0.19        0.20        0.15    
item5      0.55      0.23       0.19        0.18        0.14    

Suggest me how I can create line plots for all the items across the time with plotly express. Thanks


Solution

  • They have great examples on their documentation (https://plot.ly/python/plotly-express/#scatter-and-line-plots).

    By design it works best with tidy data so you would have a column for Date, a column for Item Number, and then a column for the value.

    from datetime import datetime, timedelta
    import numpy as np
    import pandas as pd
    
    base = datetime.today()
    dates = [base - timedelta(days=x) for x in range(10)] * 3
    cats = ['A'] * 10 + ['B'] * 10 + ['C'] * 10
    vals = np.arange(30)
    
    df = pd.DataFrame({'Date': dates, 'Category': cats, 'Value': vals})
    px.line(df, x='Date', y='Value', color='Category')