Search code examples
pythonchartsplotly

How to draw a multiple line chart using plotly_express?


I need to create a line chart from multiple columns of a dataframe. In pandas, you can draw a multiple line chart using a code as follows:

df.plot(x='date', y=['sessions', 'cost'], figsize=(20,10), grid=True)

How can this be done using plotly_express?


Solution

  • With version 4.8 of Plotly.py, the code in the original question is now supported almost unmodified:

    pd.options.plotting.backend = "plotly"
    df.plot(x='date', y=['sessions', 'cost'])
    

    Previous answer, as of July 2019

    For this example, you could prepare the data slightly differently.

    df_melt = df.melt(id_vars='date', value_vars=['sessions', 'cost'])
    

    If you transpose/melt your columns (sessions, cost) into additional rows, then you can specify the new column 'variable' to partition by in the color parameter.

    px.line(df_melt, x='date' , y='value' , color='variable')
    

    Example plotly_express output