如何根据值制作 plotly xaxis 或 zeroline 多种颜色?

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

以下代码绘制零线。我希望当 x 轴小于 0.5 时零线是不同的颜色(例如,红色),如果大于 0.5 则为绿色。我可以用 zeroline 做到这一点吗?如果没有,关于方法的建议?

    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')

您可以使用带有参数 mode='lines'go.Scatter 添加两条彩色线条作为附加轨迹。您需要先添加这些痕迹,以便它们出现在标记下方。

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()