3

I’m trying to add horizontal lines to the plot below at y=20 without success.

Thanks for the help!

import plotly.express as px
tips = px.data.tips()
fig = px.box(tips, x="time", y="total_bill")
fig.show()

enter image description here

4 Answers 4

3

If you desire to add a horizontal line that completely covers the whole of axis x, you can use a hidden axis trick (inspired by this post):

import plotly.express as px
import plotly.graph_objects as go
tips = px.data.tips()
fig = px.box(tips, x="time", y="total_bill")

# add a second axis that overlays the existing one
fig.layout.xaxis2 = go.layout.XAxis(overlaying='x', range=[0, 2], showticklabels=False)
fig.add_scatter(x = [0, 2], y = [20, 20], mode='lines', xaxis='x2',
                            showlegend=False, line=dict(dash='dash', color = "firebrick", width = 2))

fig.show()

So, the output figure will be like the following: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

You could add a custom marker with a line like so:

go.Scatter(y=[20], x=["Dinner"], mode="markers", marker_symbol=41, marker_line_color="red", marker_color="lightskyblue",
                           marker_line_width=3, marker_size=30, name="max")

See also here: https://plotly.com/python/marker-style/

Comments

1

You can add an horizontal line with add_trace:

import plotly.express as px

tips = px.data.tips()
fig = px.box(tips, x="time", y="total_bill")
fig.add_trace(go.Scatter(x=['Dinner', 'Lunch'], y=[20, 20], mode="lines", name=""))
fig.show()

It produces: horizontal line on a boxplot

1 Comment

Hi, I was wondering if you also now how to put the horizontal line only through 1 box? i.e. each box has their own line?
0

The solution that worked for me was to insert 1 item on the left side of the XAxis and 1 item on the right, then draw a line from X[0], X[1] and X[2]. In my case i needed to draw only one box in the plot.

x=[] 
y=[]

x.append("P1")
x.append("LABEL")
x.append("P2")
y.append(5)
y.append(5)
y.append(5)

fig.add_trace(go.Scatter(
    x=x,
    y=y,
    mode='lines',
    line=dict(
        color='yellow',
        width=2
     )
  )) 

then hide the labels if no need to see them.

fig.update_layout(
    xaxis=dict(showticklabels=False),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.