How can I add a single line to a scatter plot in plotly?

Hi from your question I can see that you need plotly shapes functionality and generate a horizontal line for the plot.

Please find below the code for doing the same graph you have shown in the question

Code:

from plotly.offline import iplot
import plotly.graph_objs as go


data = list(range(10))
trace = go.Scatter(
    x=list(range(len(data))),
    y=data
)
layout = {
    'shapes': [
        # Line Horizontal
        {
            'type': 'line',
            'x0': 0,
            'y0': 4,
            'x1': 10,
            'y1': 4,
            'line': {
                'color': 'rgb(50, 171, 96)',
                'width': 4
            },
        }
    ],
    'showlegend': True
}

fig = {
    'data': [trace],
    'layout': layout,
}


iplot(fig)

Output:

plotly shapes

Additional reference:

  1. plotly shapes examples

  2. plotly shapes reference


Alternatively, you could use the add_shape method, see the doc here. If you add the following code, you could add the line same as y=4 as above.

fig.add_shape(type="line",
              x0=4, 
              y0=0, 
              x1=4, 
              y1=10)

You can just add the next line:

fig.add_hline(y=4, line_width=2, line_dash='dash')

Also checkout the documentation for further deep into the features that plotly recently has added.

Tags:

Python

Plotly