Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 889
Ryan Avatar asked Apr 24 '19 03:04

Ryan


People also ask

How do you plot multiple lines in Plotly?

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.

How do you describe multiple lines on a graph?

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.


1 Answers

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

like image 174
G Hart Avatar answered Sep 28 '22 09:09

G Hart