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?
To create multiple line charts on the same plot with plotly graph objects, all you have to do is add another trace to the plot. If you look closely, you can see that I have also added the name parameter to add the labels for the legend and also explicitly added the mode='lines' to tell plotly that i want a line chart.
In a multiple line graph, there are two or more lines in the graph connecting two or more sets of data points. The independent variable is listed along the horizontal, or x, axis and the quantity or value of the data is listed along the vertical, or y, axis. Lastly, the legend, or key, states what each line represents.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With