How can I combine a line and scatter on same plotly chart?

狂风中的少年 提交于 2019-12-02 01:21:45

There are two main ways you can do this with plotly, make a ggplot and convert to a plotly object as @MLavoie suggests OR as you suspected by using add_trace on an existing plotly object (see below).

library(plotly)

#data
df <- data.frame(season=c("2000","2000","2001","2001"), game=c(1,2,1,2),value=c(1:4))

#Initial scatter plot
p <- plot_ly(df, x = game, y = value, mode = "markers", color = season)

#subset of data
df1 <- subset(df,season=="2001")

#add line
p %>% add_trace(x = df1$game, y = df1$value, mode = "line")

The answer given by @LukeSingham does not work anymore with plotly 4.5.2. You have to start with an "empty" plot_ly() and then to add the traces:

df1 <- data.frame(season=c("2000","2000","2001","2001"), game=c(1,2,1,2), value=c(1:4))
df2 <- subset(df, season=="2001")

plot_ly() %>% 
  add_trace(data=df1, x = ~game, y = ~value, type="scatter", mode="markers") %>% 
  add_trace(data=df2, x = ~game, y = ~value, type="scatter", mode = "lines")

here is a way to do what you want, but with ggplot2 :-) You can change the background, line, points color as you want.

library(ggplot2)
library(plotly)
    df_s <- df[c(3:4), ]

    p <- ggplot(data=df, aes(x = game, y = value, color = season)) +
      geom_point(size = 4) +
      geom_line(data=df_s, aes(x = game, y = value, color = season))

    (gg <- ggplotly(p))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!