Horizontal Line in Python Plotly Scatter plot

自闭症网瘾萝莉.ら 提交于 2021-01-07 03:53:12

问题


I'm looking for a way to draw two horizontal lines in a Plotly Scatter plot. My x-axis index is not fixed and keep changing everytime. So I'm looking for a Horizontal line at y = 5 and y = 18 passing horizontally across the chart

I looked here for a solution but I'm not sure how to use layouts with Plotly express

My code for scatter plot:

import plotly.express as px
df = pd.DataFrame({"x":[0, 1, 2, 3, 4,6,8,10,12,15,18], "y":[0, 1, 4, 9, 16,13,14,18,19,5,12]})
fig = px.scatter(df, x="x", y="y")
fig

回答1:


Yes, you can do that using fig.update_layout(), here is how:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({ "x":[0, 1, 2, 3, 4,6,8,10,12,15,18],
                    "y":[0, 1, 4, 9, 16,13,14,18,19,5,12]})
fig = px.scatter(df, x="x", y="y")

# add two horizontal lines
fig.update_layout(shapes=[
    # adds line at y=5
    dict(
      type= 'line',
      xref= 'paper', x0= 0, x1= 1,
      yref= 'y', y0= 5, y1= 5,
    ),
    # adds line at y=18
    dict(
      type= 'line',
      xref= 'paper', x0= 0, x1= 1,
      yref= 'y', y0= 18, y1= 18,
    )
])

fig.show()

Which produces this graph:

I don't know if there is an easier way, but this is what I would use




回答2:


These days it is simpler using vline or hline

import plotly.express as px

df = pd.DataFrame({"x":[0, 1, 2, 3, 4,6,8,10,12,15,18], "y":[0, 1, 4, 9, 
16,13,14,18,19,5,12]})

fig = px.scatter(df, x="x", y="y")
fig.add_hline(y=5)
fig.add_hline(y=18)

fig.show()


来源:https://stackoverflow.com/questions/62282794/horizontal-line-in-python-plotly-scatter-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!