How to plot multiple lines on the same y-axis using plotly express?

BUMP - Looking for a response

Hi @UdayGuntupalli,

No it is not. If you omit the the x argument , plotly will automatically set the xaxis with indices starting from 0.

fig = px.line(df, y='AAPL.High')

From what I see, you did it the right way in your sample code. I tried it to be sure and it shows 2 lines as expected. Or I don’t really understand the problem here.

Alex-

@Alexboiboi,
The plot does not have two lines, it has a line and a scatter. I am trying to have two lines, hope that clarifies the confusion.

Ah ok. For a scatter trace, if you don’t explicitly give the argument: mode='markers', mode='lines' or mode='lines+markers' or even mode='markers+lines+text', plotly chooses one by default depending on the number of points of your trace.

hope this helps, Alex-

one more way to do it would be to reshape your dataframe beforehand. For example:

df1 = df.melt(id_vars=['Date']+list(df.keys()[5:]), var_name='AAPL')
px.line(df1, x='Date', y='value', color='AAPL' )

2 Likes

@Alexboiboi,

import plotly.express as px 
import pandas as pd 
import numpy as np 

# Get some data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

# Plot 
fig = px.line(df, x='Date', y='AAPL.High')

# Only thing I figured is - I could do this 
fig.add_scatter(x=df['Date'], y=df['AAPL.Low'], mode='lines')

# Show plot 
fig.show()

However, the one thing that is not clear is, why does it not pick the column name when I add the second trace ? Appreciate your help.
image

this is because when you first create the figure via plotly.express it only contains one trace. By default plotly only shows the traces in the legend if there is are at least 2 traces. For the first trace the showlegend attribute is automatically set to False.

For the add_scatter() method on the other hand the the showlegend attribute is automatically set to True for the new trace since adding a trace implies at least 2 trace are present. But the first trace properties are unchanged, hence the lack of legend entry.

With version 4.8 of Plotly.py, you can now plot this kind of data directly from the initial px.line() call by passing multiple values for y :slight_smile:

5 Likes

Can you provide an example? The obvious syntax doesn’t work.

@microprediction try this:

import plotly.express as px 
import pandas as pd 

# Get some data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = px.line(df, x='Date', y=['AAPL.High', 'AAPL.Low'])
fig.show()
7 Likes

How can I have different rather than the same error bars on the 2 lines and how can I color the lines differently (data is here > https://www.dropbox.com/s/u2dbj0tcqz8hfhi/test_excel_import_1.xlsx?dl=0)?

import plotly.express as px
import pandas as pd

df = pd.read_excel('/Users/Jakob/Documents/python_notebooks/data/test_excel_import_1.xlsx')

fig = px.scatter(df, x='Time', y=['10 Min Sampled Avg', 'Velocity'], error_y='10 Min Std Dev')

fig.update_traces(
    name='sample 1',
    mode='markers+lines',
    error_y=dict(color='black', width=5, thickness=1),
    marker=dict(color='red', size=10),
    line=dict(color='blue', width=3),
    showlegend=True
)

fig.update_layout(template='simple_white',
    yaxis_title='Wind speed (m/s)',
    title='Continuous, variable value error bars',
    hovermode="x"
)
 
fig.show()

@windrose this is a good question, and unfortunately we don’t have a way to do that right now, you’ll have to .melt() your data to long form for this.

1 Like

Unfortunately, I don’t understand what you mean by “.melt() your data to long form for this”?
Is there a way to do it with these type of lines perhaps?

import plotly.graph_objs as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/wind_speed_laurel_nebraska.csv')
#df = pd.read_excel('/Users/Jakob/Documents/python_notebooks/data/test_excel_import_1.xlsx')

fig = go.Figure([
    go.Scatter(
        name='Measurement',
        x=df['Time'],
        y=df['10 Min Sampled Avg'],
        mode='markers',
        marker=dict(color='red', size=2),
        showlegend=True
    ),
    go.Scatter(
        name='Upper Bound',
        x=df['Time'],
        y=df['10 Min Sampled Avg']+df['10 Min Std Dev'],
        mode='lines',
        marker=dict(color="#444"),
        line=dict(width=1),
        showlegend=False
    ),
    go.Scatter(
        name='Lower Bound',
        x=df['Time'],
        y=df['10 Min Sampled Avg']-df['10 Min Std Dev'],
        marker=dict(color="#444"),
        line=dict(width=1),
        mode='lines',
        fillcolor='rgba(68, 68, 68, 0.3)',
        fill='tonexty',
        showlegend=False
    )
])
fig.update_layout(
    yaxis_title='Wind speed (m/s)',
    title='Continuous, variable value error bars',
    hovermode="x"
)
fig.show()

1 Like

Okay, just figured that it seems very easy to get these kinds of graphs

with this code

import plotly.graph_objs as go
import pandas as pd

#df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/wind_speed_laurel_nebraska.csv')
df = pd.read_excel('/Users/Jakob/Documents/python_notebooks/data/test_excel_import_1.xlsx')

fig = go.Figure([
    
    go.Scatter(
        name='Measurement 1',
        x=df['Time'],
        y=df['10 Min Sampled Avg'],
        mode='markers+lines',
        marker=dict(color='red', size=2),
        showlegend=True
    ),
    go.Scatter(
        name='Upper Bound',
        x=df['Time'],
        y=df['10 Min Sampled Avg']+df['10 Min Std Dev'],
        mode='lines',
        marker=dict(color="#444"),
        line=dict(width=1),
        showlegend=False
    ),
    go.Scatter(
        name='Lower Bound',
        x=df['Time'],
        y=df['10 Min Sampled Avg']-df['10 Min Std Dev'],
        marker=dict(color="#444"),
        line=dict(width=1),
        mode='lines',
        fillcolor='rgba(68, 68, 68, 0.3)',
        fill='tonexty',
        showlegend=False
    ),
    
    go.Scatter(
        name='Measurement 2',
        x=df['Time'],
        y=df['Velocity'],
        mode='markers+lines',
        marker=dict(color='blue', size=2),
        showlegend=True
    ),
    go.Scatter(
        name='Upper Bound',
        x=df['Time'],
        y=df['Velocity']+df['SEM'],
        mode='lines',
        marker=dict(color="#444"),
        line=dict(width=1),
        showlegend=False
    ),
    go.Scatter(
        name='Lower Bound',
        x=df['Time'],
        y=df['Velocity']-df['SEM'],
        marker=dict(color="#444"),
        line=dict(width=1),
        mode='lines',
        fillcolor='rgba(68, 68, 68, 0.3)',
        fill='tonexty',
        showlegend=False
    )
])
fig.update_layout(
    yaxis_title='Wind speed (m/s)',
    title='Continuous, variable value error bars',
    hovermode="x"
)
fig.show()

However, I don’t understand why that should not also work with the figure that has error bars instead of a continous line?

1 Like

This comment made my new years day!

Thanks!

hi i went though it and created a chart with facet. problem is to assign different colors to 2 series in facet.

1 Like

I would like to have the following plot, but instead of 3 measurements i have ca. 300.

I am able to plot all the y-columns as follows:

fig = px.line(df, x=‘ID’, y= df.columns)

I am able to plot the grey area as follows:

fig = go.Figure([
go.Scatter(
name=‘Upper Bound’,
x=df[‘ID’],
y=df.Rate_max,
mode=‘lines’,
marker=dict(color="#444"),
line=dict(width=0),
showlegend=False
),
go.Scatter(
name=‘Lower Bound’,
x=df[‘ID’],
y=df.Rate_min,
marker=dict(color="#444"),
line=dict(width=0),
mode=‘lines’,
fillcolor=‘rgba(68, 68, 68, 0.3)’,
fill=‘tonexty’,
showlegend=False
)
])

What i am not able to do is to plot them together.
In Plotly (go.Scatter) i need to define every column separately.

Is there any how how to set up

> y= df.columns
in Go.Scatter?

I have tried to melt the df by:

df_long=pd.melt(df , id_vars=[‘ID’])

but it gives a df, where all the time series are being plotted continuously (not all starts in the same point):

Is there possieble to melt the df in different way, or how could i get following plot, without to define all y-columns?

Is there any way how to combine plotting of Plotly (go.Scatter) with Plotly Express (px.line)?

OKAY, the problem is solved:

1 Like

Is there a solution to this now?