Reputation: 61
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
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
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!
Upvotes: 1
Views: 421
Reputation: 61
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.
Upvotes: 1