plotly: do not connect gaps in plotly express line graph
Asked Answered
B

3

5

I have created the above plot using plotly express:

import plotly.express as px

fig = px.line(mini_df, 
              x=mini_df.index,
              y=mini_df[mini_df.columns[1]],
              color=mini_df[mini_df.columns[0]])

I am trying to make a line plot which has a changing color depending on the value of some column.

This works, but unfortunately, there is an ugly connection between the end of good status and the beginning of the 2nd good status phase.

Is it possible, using express, to remove this ugly connection? Or do I need to use plotly graph_objects to achieve this?

Beckham answered 6/1, 2020 at 21:39 Comment(0)
G
3

You can append .update_traces(connectgaps=False) to mutate the figure that's generated with Plotly Express. PX uses graph_objects under the hood so any update method works here.

Ginglymus answered 7/1, 2020 at 3:33 Comment(2)
I think this works if there is one gap, but not if the color column switches values back and forth multiple times. See this questionUnrelenting
It didn't work for me.Theodolite
P
2

There are some other solutions mentioned here: Plotly: How to create a line plot of a time series variable that has a multiple-color label?

Unfortunately none are as simple as nicolaskruchten's suggestion above. However, I may be missing something but the connectgaps=False solution doesn't work for me. Perhaps because there are no NaNs in the data when dissecting a continuous time series like this. E.g. in the above example the x-axis data for the blue trace would be [..., 3750, 4250, ...]. There's a 'gap' between 3750 and 4250, but no NaN..

Pederasty answered 13/5, 2021 at 3:24 Comment(0)
G
0

To make .update_traces(connectgaps=False) work you have to generate the missing dates for the all the colors, since that is how it figures out that data is missing (it does not understand the datetime gap automatically). An option is to put your date and color variable in the index and then reindex it with all the possible combinations of the two pd.MultiIndex.from_product, then the lines won't be connected.

Galaxy answered 15/2 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.