pythonplotlyscatter-plot

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


Consider the following MWE to draw a scatter plot using the python API to plotly:

import plotly.plotly as py
import plotly.graph_objs
import plotly.offline
plotly.offline.init_notebook_mode()

data = list(range(10))
trace = plotly.graph_objs.Scatter(
    x=list(range(len(data))),
    y=data
)
plotly.offline.iplot([trace])

enter image description here

What if I now want to add a (say) horizontal line to this plot? I went through the documentation, for example the section on line and scatter and that on line charts, but none of the examples seem to cover how to overlay different plots, or simply draw straight lines and similar shapes.

A naive approach to do this is to just add the line as a second scatter plot, like the following:

import plotly.plotly as py
import plotly.graph_objs
import plotly.offline
plotly.offline.init_notebook_mode()

data = list(range(10))
trace = plotly.graph_objs.Scatter(
    x=list(range(len(data))),
    y=data
)
trace_line = plotly.graph_objs.Scatter(
    x=list(range(len(data))),
    y=[4] * len(data),
    mode='lines'
)
plotly.offline.iplot([trace, trace_line])

enter image description here

This approach seems however to be suboptimal: aside for the verbosity required to add a single line, it also makes me manually "sample" the straight line, and it adds the line height to the tooltip on mouse hover.

Is there a better approach to achieve this?


Solution

  • 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