Visualise Multiple lines in plotly express plot

Viewed 3854

I am currently experimenting with plotly expess graphs to plot multiple sensor measurements. I have a csv data set which I read with pandas looking a like this (df_full_data):

data example

The data is used within a call back graph where two dropdown fields are used as input to define the year (year_value) and which sensors (hoved) should be shown in the graph.

year_data = df_full_data[df_full_data.years == int(year_value)]
filtered_sensor = year_data[year_data['ID'].isin(hoved)]

I use then px.line to plot the data.

figure = px.line(filtered_sensor, x=filtered_sensor['time'], y=filtered_sensor['water_m'], color=filtered_sensor['ID'], title='Sensor Meting')

everything is working fine when one sensorID is selected, but when I select two sensors the data will be shown behind each other. Meaning that first Sensor 58 data will be shown from 01/01/2019 till 31/12/2010, and the x axis will then start again from 01/01/2019 and plot the data of sensor 64.

plot result with two data sets.

I would like to plot the two graphs above each other/ on top of each other, and I guess this has something to do with how I sort or structure my panda table and how plotly will represent it, but I have no Idea how to accomplish this. Any idea or tips how to change it so the data will be represented above each other like this:

correct graph example

Tried I have tried to add traces for each sensor with:

fig = go.Figure()
for subset_id, subset in year_data.groupby('ID'):
    fig.add_trace(
        px.line(
            subset,
            x=subset['time'],
            y=subset['water_m'],
            color=subset['ID'],
            title=subset_id
        ).data[0]
    )

But it still gives me the same behaviour that the sensors are plotted in serie and not parallel to each other. enter image description here

2 Answers

I think what you are looking for is to add a second or even third trace to your plot.

Snippet from Documentation of plotly express

fig.add_trace(
    go.Scatter(
        x=[2, 4],
        y=[4, 8],
        mode="lines",
        line=go.scatter.Line(color="gray"),
        showlegend=False)
)

Does this work?

import plotly.express as px
import plotly.graph_objects as go

fig = go.Figure()

for subset_id, subset in year_data.groupby('ID'):
    fig.add_trace(
        px.line(
            subset,
            x=subset['time'],
            y=subset['water_m'],
            color=subset['ID'],
            title=subset_id
        )
    )
Related