How to make the plotly xaxis or zeroline multiple colors based on value?

Viewed 227

The below code plots a zeroline. I would like the zeroline to be a different color (e.g., red) when the x-axis is less than 0.5 and green if greater than 0.5. Can I do this with zeroline? If not, suggestions on approach?

    fig = go.Figure()
    # Adds the two dots
    fig.add_trace(go.Scatter(
        x=[0.3, 0.6], y=[0,0], mode='markers', marker_size=20,
    ))
    fig.update_xaxes(showgrid=False)
    fig.update_yaxes(showgrid=False, 
                     zeroline=True,
                     zerolinecolor='black',
                     zerolinewidth=3,
                     showticklabels=False)
    fig.update_layout(height=200, plot_bgcolor='white')

enter image description here

1 Answers

You can add the two colored lines as additional traces using go.Scatter with the argument mode='lines'. You'll want to add these traces first so that they appear below the markers.

import plotly.graph_objects as go

fig = go.Figure()

## add the two lines
fig.add_trace(go.Scatter(
    x=[0.25, 0.5], y=[0,0], mode='lines', line=dict(color="red", width=3),
))
fig.add_trace(go.Scatter(
    x=[0.5, 0.65], y=[0,0], mode='lines', line=dict(color="green", width=3),
))

# Adds the two dots using plotly's default first color
fig.add_trace(go.Scatter(
    x=[0.3, 0.6], y=[0,0], mode='markers', marker_size=20, marker_color="rgb(99,114,242)"
))

fig.update_xaxes(showgrid=False)
fig.update_yaxes(showgrid=False, 
                    zeroline=True,
                    zerolinecolor='black',
                    zerolinewidth=3,
                    showticklabels=False)


fig.update_layout(height=200, plot_bgcolor='white')
fig.show()

enter image description here

Related