Having multiple sets of Y-values (on the same y-axis) in a subplot

For a single plot without subplots, it’s easy:

fig = px.line(covid, x=covid[‘ObservationDate’], y=covid.columns[2:])

where, covid.columns returns:
Index([‘Country/Region’, ‘ObservationDate’, ‘Confirmed’, ‘Recovered’, ‘Deaths’], dtype=‘object’)

But this is where I get stumped - when I want to do the same with subplots. For example:

fig = make_subplots(rows=3)
fig.add_trace(
    go.Line(x=covid_china['ObservationDate'], y=covid_china['Confirmed']),
    row=1, col=1
)
fig.add_trace(
    go.Line(x=covid_china['ObservationDate'], y=covid_china['Recovered']),
    row=1, col=1
)
fig.add_trace(
    go.Line(x=covid_china['ObservationDate'], y=covid_china['Deaths']),
    row=1, col=1
)
fig.add_trace(
    go.Line(x=covid_us['ObservationDate'], y=covid_us['Confirmed']),
    row=2, col=1
)
fig.add_trace(
    go.Line(x=covid_us['ObservationDate'], y=covid_us['Recovered']),
    row=2, col=1
)
fig.add_trace(
    go.Line(x=covid_us['ObservationDate'], y=covid_us['Deaths']),
    row=2, col=1
)
fig.add_trace(
    go.Line(x=covid_india['ObservationDate'], y=covid_india['Confirmed']),
    row=3, col=1
)
fig.add_trace(
    go.Line(x=covid_india['ObservationDate'], y=covid_india['Recovered']),
    row=3, col=1
)
fig.add_trace(
    go.Line(x=covid_india['ObservationDate'], y=covid_india['Deaths']),
    row=3, col=1
)
fig.update_layout(height=600, width = 800)
fig.show()

I could not pass in multiple sets of y-values to go.Line(); the only way to make it work was as above - calling a .add_trace() for each set of y-values. Help?

Hi @fanyang welcome to the forums.

This is actually because plotly.express creates different graph_object traces for you if the y argument is a list. What you could do is the following:

import pandas as pd
import plotly.express as px
from plotly.subplots import make_subplots 
import numpy as np

df = pd.DataFrame(np.random.randint(0,255,size=(100,4)), columns=list('ABCD'))
fig = make_subplots(rows=2)

sub1 = px.line(df, y=['A', 'B'])
sub2 = px.line(df, y=['C', 'D'])

fig.add_traces(sub1.data, rows=1, cols=1)
fig.add_traces(sub2.data, rows=2, cols=1)
fig.show()

newplot (16)

The key is here to extract the data (traces) from the px.line() figures

Gotcha - so you are creating 2 line graphs (sub1 and sub2), extracting the data from them (using .data), then adding them as subplots to a single graph (fig) by using .add_traces(). Thanks very much! This makes good sense.

I found another solution that actually worked well also:

for col in covid_china.columns[2:]:
    
    fig.add_trace(
        go.Line(x=covid_china['ObservationDate'], y=covid_china[col]), row=1, col=1
    )
1 Like

Correct. Looping is always an option :raised_hands: :joy: