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

Viewed 19934

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?

3 Answers

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.

Related