19

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)
vestland
  • 55,229
  • 37
  • 187
  • 305
gboge
  • 373
  • 1
  • 2
  • 6
  • 1
    If you've received the answers you needed, please consider marking one of the suggestions as the accecpted solution – vestland May 14 '20 at 06:46

5 Answers5

21

You could also use fig.add_hline(y=1) --> see https://plotly.com/python/horizontal-vertical-shapes/

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_hline(y=40, line_width=3, line_dash="dash", line_color="green")


fig.show()
Shunya
  • 2,344
  • 4
  • 16
  • 28
Moritz Wittig
  • 251
  • 2
  • 5
17

Short answer, and a general solution:

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

Details and specifics about OP's question

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.

vestland
  • 55,229
  • 37
  • 187
  • 305
  • 1
    thank u. im new to CS. can you recommend any good plotly tutorial for beginners like myself? I'm pretty much copying and pasting stuff from the plotly website at the moment with no clue of what is what. – gboge Mar 29 '20 at 23:24
  • @gboge - To be honest, that's how I learned plotly ... just by using it and **constantly** referring to the docs - which are brilliantly done. The thing that helped be the most was just realising the data structure is just a bunch of `list`s and `dict`s. All the best! – S3DEV Mar 30 '20 at 08:10
  • 1
    @gboge The guys at plotly have put together an absolutely fabulous documentation for their product. You'll find everything [here](https://plotly.com/python/). And you'll find some great details at [Getting started](https://plotly.com/python/getting-started/) and [Fundamentals](https://plotly.com/python/plotly-fundamentals/). – vestland Mar 30 '20 at 21:44
  • @gboge For a great visualization of the data and layout structure of a plotly plot, take a look at [this](https://www.r-craft.org/r-news/plotly-an-interactive-charting-library/). – vestland Mar 30 '20 at 21:46
4

If you use subplots, then this is the easiest way I found to add an other line to a subplot. this example draws a horizontal line at y=80 for all x values

from plotly.subplots import make_subplots

fig = make_subplots(rows=2, cols=1,
                    shared_xaxes=True,
                    vertical_spacing=0.02)
[some graph]

fig.add_trace(go.Scatter(
        name='Y=80',
        x = [df['date'].min(), df['date'].max()],
        y = [80, 80],
        mode = "lines",
        marker = dict(color = 'rgba(80, 26, 80, 0.8)')
    ),row=1, col=1)

i found the solution on github :

endo.anaconda
  • 2,449
  • 4
  • 29
  • 55
2
df = df
fig = px.scatter(df, x="date", y="growth_factor", mode = 'lines',
      hover_name=df['growth_factor'] )

fig.update_layout(shapes=[
dict(
  type= 'line',
  yref= 'y', y0= 1, y1= 1,   # adding a horizontal line at Y = 1
  xref= 'paper', x0= 0, x1= 1
     ) 
])

fig.show()

DSBLR
  • 555
  • 5
  • 9
1

You’re adding the line to your fig object, but fig is not getting passed into the iplot() function, only your data. So only the trace is getting plotted.

If you're using a late version of plotly, the new syntax allows you to create this plot simply using the fig object, like:

from plotly import graph_objects as go

fig = go.Figure()

# Contrived dataset for example.
x = [1, 2, 3, 4]
y = [i**2 for i in x]

fig.add_trace(go.Scatter(
              x=x,
              y=y,
              mode = 'lines',
              name = 'growth_factor'))

fig.add_shape(type='line',
              x0=min(x),
              y0=5,
              x1=max(x),
              y1=5,
              line=dict(color='Red'))

fig.update_shapes(dict(xref='x', yref='y'))

fig.show()

Here are the plotly docs for convenience.

S3DEV
  • 8,768
  • 3
  • 31
  • 42