`add_trace` with `type = 'scatter', mode = 'lines'` works differently from `add_lines`
Nobody has claimed this yet.
- Dominant language
- R
- Stars
- 2.7k
- Forks
- 641
- PR merge metrics
- No merged PRs in 30d
Description
When plotting a regression line with confidence intervals, add_trace with type = 'scatter', mode = 'lines' works differently from add_lines. The latter works while the former fails (see examples).
Looks like add_trace(type = 'scatter', mode = 'lines', ...) attempts to connect datapoints pairwise instead of sequentially.
# load packages
require(dplyr)
require(plotly)
# prep data
setosa <- iris |>
filter(Species == "setosa") |>
mutate(fit = predict(lm(Sepal.Width ~ Sepal.Length), interval = "conf")[, "fit"],
lwr = predict(lm(Sepal.Width ~ Sepal.Length), interval = "conf")[, "lwr"],
upr = predict(lm(Sepal.Width ~ Sepal.Length), interval = "conf")[, "upr"])
## Compare plots ##
# plot 1: add_lines works
plot_ly(data = setosa, x = ~Sepal.Length) |>
add_trace(y = ~Sepal.Width,
type = 'scatter',
mode = 'markers',
showlegend = FALSE) |>
add_lines(y = ~upr, # add_lines works
color = I("#2ca02c"),
name = 'CI upper') |>
add_lines(y = ~lwr, # add_lines works
color = I("#2ca02c"),
alpha = 0.2,
fill = 'tonexty',
name = 'CI lower') |>
add_trace(y = ~fit, # add_trace works
type = 'scatter',
mode = 'lines',
name = 'Predicted')
# plot 2: replaced add_lines with add_trace, no other changes
plot_ly(data = setosa, x = ~Sepal.Length) |>
add_trace(y = ~Sepal.Width,
type = 'scatter',
mode = 'markers',
showlegend = FALSE) |>
add_trace(y = ~upr, # add_trace doesn't work
type = 'scatter',
mode = 'lines',
color = I("#2ca02c"),
name = 'CI upper') |>
add_trace(y = ~lwr, # add_trace doesn't work
type = 'scatter',
mode = 'lines',
color = I("#2ca02c"),
alpha = 0.2,
fill = 'tonexty',
name = 'CI lower') |>
add_trace(y = ~fit, # here add_trace works as it should
type = 'scatter',
mode = 'lines',
name = 'Predicted')
Output
Plot 1:
Plot 2:
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the add_trace and add_lines entry points in the R plotting API and reproduce the supplied iris regression example. Compare how the two functions handle scatter traces with mode = 'lines', then verify that replacing add_lines with add_trace produces the same sequential confidence-interval lines and fill.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- r
- Domain
- data-visualization
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100