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])
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])
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?
You can use the boxmean property to add the mean as a dashed line. See https://plot.ly/python/box-plots/#box-plot-styling-mean--standard-deviation.
A scatter plot can be created using the function plot(x, y). The function lm() will be used to fit linear models between y and x. A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().
Adding Traces To Subplotsmake_subplots() , then supplying the row and col arguments to add_trace() can be used to add a trace to a particular subplot. This also works for figures created by Plotly Express using the facet_row and or facet_col arguments.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With