In Plotly (python), how to disconnect a lines when no values?
Question:
In Plotly (Python), I would like to disconnect a line when there is no value.
df = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])
idx = [1,2, 4,5, 7,8]
fig = go.Figure()
line = go.Scatter(x=df.index[idx], y=df['A'][idx])
fig.add_trace(line)
fig.show()
In this example, I expected to plot three separate lines as idx
is not continuous numbers, but it plots one single line.
How to gap when idx
has missing values?
Answers:
You could try adding in a column, keeping the desired values for A and adding a null value for segments you don’t want plotted.
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])
idx = [1,2, 4,5, 7,8]
df['a'] = np.where(df.reset_index().index.isin(idx), df['A'], np.nan)
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df['a']))
fig.show()
Alternatively, if you don’t want to add a new column, you could just add the trace as
fig.add_trace(go.Scatter(x=df.index, y=np.where(df.reset_index().index.isin(idx), df['A'], np.nan)))
In Plotly (Python), I would like to disconnect a line when there is no value.
df = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])
idx = [1,2, 4,5, 7,8]
fig = go.Figure()
line = go.Scatter(x=df.index[idx], y=df['A'][idx])
fig.add_trace(line)
fig.show()
In this example, I expected to plot three separate lines as idx
is not continuous numbers, but it plots one single line.
How to gap when idx
has missing values?
You could try adding in a column, keeping the desired values for A and adding a null value for segments you don’t want plotted.
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.DataFrame(range(2,12), index=pd.date_range(start='2010-01-01', freq='d', periods=10), columns=['A'])
idx = [1,2, 4,5, 7,8]
df['a'] = np.where(df.reset_index().index.isin(idx), df['A'], np.nan)
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df['a']))
fig.show()
Alternatively, if you don’t want to add a new column, you could just add the trace as
fig.add_trace(go.Scatter(x=df.index, y=np.where(df.reset_index().index.isin(idx), df['A'], np.nan)))