Ploting x and y with lists

I want to plot line chart with plotly using the following data structure:

Name	Time	Values
Name1	[0.0, 5.0, 10.0, 15.0, 20.0, 30.0, 40.0]	[0.0, 4.0, 28.0, 48.0, 54.3, 85.2, 88.3]
Name2	[0.0, 5.0, 10.0, 15.0, 20.0, 30.0]	[0.0, 4.0, 48.0, 88.0, 94.1, 95.2]

Code:

app.layout = html.Div([
    html.H1('My Plotly Graph'),
    dcc.Graph(
        id='my-graph',
        figure=px.line(df, x='Time', y='Values', color='Name')
    )
])

What I get (result) is very different from expected. Any suggestions how could I plot data in lists? Is there a direct way or is converting df unavoidable here?

Result:

Expected:

HI @mich2210 , how do you create your df? Could you add this code so we can just copy& paste it?

I think you need to explode your dataframe then use it to create your Graph.

import pandas as pd

import numpy as np
import plotly.express as px
df = pd.DataFrame({'Name': ['Name1','Name2'], 
                    'Time': [[0.0, 5.0, 10.0, 15.0, 20.0, 30.0, 40.0],[0.0, 5.0, 10.0, 15.0, 20.0, 30.0]],
                    'Values': [[0.0, 4.0, 28.0, 48.0, 54.3, 85.2, 88.3],[0.0, 4.0, 48.0, 88.0, 94.1, 95.2]]})

cols = ['Time','Values']
df1 = pd.concat([df[x].explode().to_frame()
                      .assign(g=lambda x: x.groupby(level=0).cumcount())
                      .set_index('g', append=True) 
                for x in cols], axis=1)

df = df.drop(cols, axis=1).join(df1.droplevel(1))


fig=px.line(df, x='Time', y='Values', color='Name')
fig.show()

That works. Thanks. I thought there was a direct way with plotly to input lists in case like mine.

1 Like