Help: Graphing 1 line with 2 colors in plotly express

I’m trying to plot time series data so that I have 1 single line with markers that is colored by 1 variable, where the value is either 0 or 1. Been looking at solutions for hours and can’t find a solution that works for my scenario.

Current Code:

 fig_machine_time = px.line(filtered_machine_time_data, x = 'graph_ID', y= 'delta', color = 'color_code', markers = True,
                                  color_discrete_map = {'0': 'grey','1': '#39FF14'})

Where color_code is either 0 or 1.


The output is very close, but I don’t want the gaps to be connected. This is how I would like the plot to look (done in R, slightly different data, and different colors):


You can use fig.update_traces(connectgaps=False) to remove the lines connecting gaps.

I don’t think there is a way to have two distinct colors in the same trace, but your approach looks good unless you want a single legend item for both traces (colors). If you need this feature, please let me know that I can point you out to a solution.

Unfortunately, fig.update_traces(connectgaps=False) does not work. The lines still connect. I think I read on stack overflow that that command only works when there are 2 of each group: 0, 1, 0, 1. I have many more observations in each group.

I see. I think that it is more because px.line does not recognize the “skipped” points (maybe timestamps, not sure what the x-axis is…).

You can try to force it by filling the values in the 0 curve with nans when the points in curve 1 are defined. In other words, replace your y column by two columns, one for 0 and the other for 1.

1 Like

Oh okay. That might work! Do you have an example of how the plotting code would work if there were 2 columns: group_0 y observations and group_1 y observations. Thank you for your time and help!!

No problem. Here is one quick example of what I meant using the stocks data in plotly express:

import numpy as np
import as px

df =[["date", "FB"]]

df["FB_0"] = df["FB"].apply(lambda x: x if x >= 1 else np.nan)
df["FB_1"] = df["FB"].apply(lambda x: x if x < 1 else np.nan)

fig = px.line(df, x="date", y=["FB_0", "FB_1"])

There might be more efficient ways to do it, as you seem to have lots of points. I believe adding one single nan in each gap should be enough.

1 Like