Python – Plotly: How to add a horizontal line to a line graph

plotlyplotly-pythonpython

I made a line graph with the code below and I'm trying to add a horizontal line at y=1. I tried following the instructions on the plotly site but it is still not showing. Does anyone know why?

date = can_tot_df.date
growth_factor = can_tot_df.growth_factor

trace0 = go.Scatter(
            x=date,
            y=growth_factor,
            mode = 'lines',
            name = 'growth_factor'
)

fig = go.Figure()
fig.add_shape(
        type='line',
        x0=date.min(),
        y0=1,
        x1=date.max(),
        y1=1,
        line=dict(
            color='Red',
        )
)


data = [trace0]
iplot(data)

Best Answer

It's hard to tell exactly what's wrong without a sample of your data. What I can tell for sure is that you're missing the arguments xref and yref to specify that the line is drawn as units of your y and x axis. Judging by your sample code, this is what you'd like to do since you're specifying your x-values in terms of dates.

Also, you don't need to worry about iplot for newer versions of plotly. You can display your chart just as easily by just running fig.show(). The figure and code sample below will show you how to use fig.show() and how to define your lines in terms of axis units.

Plot:

enter image description here

Code:

import plotly.graph_objects as go
import numpy as np

x = np.arange(10)

fig = go.Figure(data=go.Scatter(x=x, y=x**2))

fig.add_shape(type='line',
                x0=0,
                y0=40,
                x1=8,
                y1=40,
                line=dict(color='Red',),
                xref='x',
                yref='y'
)


fig.show()

An alternative to xref='x' is xref='paper'. Now you can specify x0 as a float between 0 and 1 spanning from the start and end of the plot.