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