Home > Software design >  Adding a smoothed line to a plotly chart
Adding a smoothed line to a plotly chart

Time:11-20

I have a scatterplot and I would like to add a smoothed connecting line between points. I am able to do this using ggplot and a plotly wrapper without issue:

library(tidyverse)
library(plotly)

dat <- data.frame(x = c(0.89910345, 0.994439176, 0.881675547, 0.993289873, 0.990991268, 0.980292298, 0.984415918, 0.993125417, 0.990463749, 0.994603633, 0.965500006, 0.990827284, 0.993618787, 0.992961434, 0.938100735, 0.957212413, 0.981905481, 0.993289873, 0.906759406, 0.991483218),
                  y = c(0.819935601, 0.803471076, 0.820239219, 0.807804144, 0.812154115, 0.815320137, 0.814483142, 0.808271728, 0.812404613, 0.802747176, 0.816710715, 0.812240861, 0.806708415, 0.808695239, 0.818457407, 0.817328889, 0.815076674, 0.807785879, 0.819725289, 0.811638314))

ggplotly(dat %>% 
  ggplot(aes(x = x, y = y))  
  geom_point()  
  geom_line())

enter image description here

However, I would like to do this using native plotly syntax. When I try do to so however, I get the following. Can anyone tell me what is wrong with my code?

dat %>% 
  plot_ly(x = ~x,
            y = ~y) %>% 
  add_trace(type = "scatter",
            mode = "markers") %>% 
  add_trace(mode = "line")

enter image description here

CodePudding user response:

You could try using geom_smooth rather than geom_line

ggplotly(dat %>% 
           ggplot(aes(x = x, y = y))  
           geom_point()  
           geom_smooth(method = "loess", se=FALSE, color="black"))

example1

or if you actually wanted to use geom_line. You can use spline

spline_int <- as.data.frame(spline(dat$x, dat$y))

ggplotly(dat %>% 
           ggplot(aes(x = x, y = y))  
           geom_point()  
           geom_line(data = spline_int, aes(x = x, y = y)))

example2

If you want to solely use plotly you can add a shape to the line

dat %>% 
  plot_ly(x = ~x,
          y = ~y) %>% 
  add_trace(type = "scatter",
            mode = "markers") %>% 
  add_lines(line = list(shape = "linear")) 

example3

  • Related