简体   繁体   中英

Python Plotly - add horizontal line to box plot

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

在此处输入图像描述

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: 箱线图上的水平线

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/

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: 在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM