rsgny
rsgny

Reputation: 635

Plotly add_hline() doesn't work with simple_white template

I was attempting to add a horizontal line to a Plotly graph using Plotly's add_hline(). It works perfectly fine so long as I do not use the simple_white template. The MWE is here:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_hline(y=0.9, line_dash='dash', line_color='Red')
fig.update_layout(width=400, height=400,
                  # template='simple_white'
                  )
fig.show()

Without the template='simple_white' line, the add_hline() works as expected. With that template though, and with no other changes, the plot is the same but without the horizontal line.

enter image description here enter image description here

Upvotes: 11

Views: 6336

Answers (2)

Peter
Peter

Reputation: 1076

I can't say why this happens, but you can get around it by explicitly specifying line_width and opacity for the horizontal line, without messing with the template:

fig.add_hline(y=0.9, opacity=1, line_width=2, line_dash='dash', line_color='Red')

If you only specify line width, the line looks washed out, possibly some of the themes (seaborn and ggplot2 in addition to plotly_white) change these two parameters?

Upvotes: 8

Derek O
Derek O

Reputation: 19610

I am not sure why this occurs, but most likely the simple_white template renders over the annotation, or the background color supercedes the annotation.

Regardless of the reason, you can recreate the simple_white template by setting the plot background color to be white, then make the axes black, and add the tickmarks on the outside.

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_hline(y=0.9, line_dash='dash', line_color='Red')
fig.update_layout(
    width=400, 
    height=400,
    plot_bgcolor="white",
    xaxis=dict(linecolor="black"),
    yaxis=dict(linecolor="black")
    # template='simple_white'
    )
fig.update_xaxes(ticks="outside")
fig.update_yaxes(ticks="outside")
fig.show()

enter image description here

Upvotes: 0

Related Questions