Plotly line, changing colour to NaN segments

Question:

I have the following code

import plotly.express as px
import pandas as pd
import numpy as np

df = pd.DataFrame([1, None, None, 4, 6, None], columns=["y"])
df["x"] = [1, 2, 3, 4, 5, 6]
df["completed"] = [1, 0, 0, 1, 1, 0]

fig = px.line(df, x="x", y="y", markers=True, color="completed")

fig.show()

That results in the following plot

enter image description here

But I have to highlight (change the color line to red and add a dot point) in the cases that the dataframe has NaN value like in the following plot
enter image description here

Is there any way to do that easily? I have been looking for it but I’m not able to find a suitable solution.

Thanks in advance!

Asked By: carluqcor98

||

Answers:

Found a solution using this https://community.plotly.com/t/change-color-of-continuous-line-based-on-value/68938/2

import plotly.express as px
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import itertools as it

df = pd.DataFrame([1, None, None, 4, 6, None, 2, 1], columns=["y"])
df["x"] = [1, 2, 3, 4, 5, 6, 7, 8]
df["completed"] = [1, 0, 0, 1, 1, 0, 1, 1]

fig = go.Figure()


# generate color list
df.loc[df["y"].isna(), "line_color"] = "red"
df.loc[df["y"].isna(), "line_type"] = "dash"


df.loc[df["y"].notna(), "line_color"] = "black"
df.loc[df["y"].notna(), "line_type"] = "solid"

df["y"] = df["y"].interpolate(method="index")

# create coordinate  pairs
x_pairs = it.pairwise(df["x"])
y_pairs = it.pairwise(df["y"])

for x, y, line_color, line_type in zip(
    x_pairs,
    y_pairs,
    df["line_color"].values,
    df["line_type"].values,
):
    # create trace
    fig.add_trace(
        go.Scatter(
            x=x,
            y=y,
            mode="lines",
            line=dict(color=line_color, dash=line_type),
        )
    )


fig.show()

This is the new output for the plot.

enter image description here

Answered By: carluqcor98
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.