Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add_trace with type = 'scatter', mode = 'lines' works differently from add_lines #2326

Open
baranovskypd opened this issue Dec 28, 2023 · 0 comments

Comments

@baranovskypd
Copy link

baranovskypd commented Dec 28, 2023

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:
add_lines_works

Plot 2:
add_trace_doesnt_work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant