Plotly add_hline() not working with secondary axis

Viewed 719

I am trying to add an hline shape in a plotly graph using a secondary y-axis. The plot correctly shows the data for the two distinct y-axes, but the hline is being plotted on primary axis despite using yref='y2' in the add_hline function.

I realize that I can work around this using add_shape instead of hline, but I was trying to determine if I was doing something wrong.

import plotly.express as px
import plotly.graph_objects as go
import numpy as np

# simple example with hline
df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_traces(go.Scatter(y=np.arange(1, 7), mode="lines+markers", yaxis='y2'))
fig.add_hline(y=2, line_dash='dash', line_color='Red', yref='y2')

fig.update_layout(
    width=400,
    height=400,
    plot_bgcolor="white",
    xaxis=dict(linecolor="black"),
    yaxis=dict(linecolor="black"),
    yaxis2=dict(
        title="yaxis2 title",
        overlaying="y",
        side="right",
        linecolor="black",
    )
)
fig.update_xaxes(ticks="outside")
fig.update_yaxes(ticks="outside")
fig.show()

enter image description here

1 Answers

You may have found a bug in Plotly's add_hline method! I can open a bug report for the Plotly team to look into.

For now, you can use the add_shape method and set the parameters: xref="paper", x0=0, x0=1 to cover the entire width of the figure. Using yref="y2" and setting both y0=2 to y1=2 works as expected.

import plotly.express as px
import plotly.graph_objects as go
import numpy as np

# simple example with hline
df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_traces(go.Scatter(y=np.arange(1, 7), mode="lines+markers", yaxis='y2'))

## this may be a bug
# fig.add_hline(y=2, line_dash='dash', line_color='Red', yref='paper')

fig.add_shape(type="line", 
    xref="paper", yref="y2",
    x0=0, y0=2, x1=1, y1=2,
    line=dict(
        color="red",
        dash="dash"
    ),
)

fig.update_layout(
    width=400,
    height=400,
    plot_bgcolor="white",
    xaxis=dict(linecolor="black"),
    yaxis=dict(linecolor="black"),
    yaxis2=dict(
        title="yaxis2 title",
        overlaying="y",
        side="right",
        linecolor="black",
    )
)
fig.update_xaxes(ticks="outside")
fig.update_yaxes(ticks="outside")
fig.show()

enter image description here

Related