Search code examples
pythonplotly

python plotly - multiple fragmented lines in same trace


I currently have the following code:

import pandas as pd

df = pd.DataFrame({'x1': [1,7,15], 'x2': [5,10,20]})
df

enter image description here

import plotly.graph_objects as go
fig = go.Figure()
for row in df.iterrows():
    row_data = row[1]
    fig.add_trace(go.Scatter(x=[row_data['x1'], row_data['x2']], y=[0,0], mode='lines',
                            line={'color': 'black'}))
fig.update_layout(showlegend=False)
fig.show()

enter image description here

This produces the required result. However, if I have 30k traces, things start to get pretty slow, both when rendering and when working with the plot (zooming, panning). So I'm trying to figure out a better way to do it. I thought of using shapes, but then I loos some functionalities that only traces have (e.g. hover information), and also not sure it'll be faster. Is there some other way to produce fragmented (non-overlapping) lines within one trace?
Thanks!

Update:
Based on the accepted answer by @Mangochutney, here is how I was able to produce the same plot using a single trace:

import numpy as np
import plotly.graph_objects as go

x = [1, 5, np.nan, 7, 10, np.nan, 15, 20]
y = [0, 0, np.nan, 0, 0, np.nan, 0, 0]
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode='lines'))
fig.update_layout(showlegend=True)
fig.show()

enter image description here


Solution

  • By default you can introduce gaps in your go.scatter line plot by adding additional np.nan entries where you need them. This behavior is controlled by the connectgaps parameter: see docs

    E.g.: go.Scatter(x=[0,1,np.nan, 2, 3], y=[0,0,np.nan,0,0], mode='lines') should create a line segement between 0 and 1 and 2 and 3.