简体   繁体   中英

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

The two separate charts created from data.frame work correctly when created using the R plotly package.
However, I am not sure how to combine them into one (presumably with the add_trace function)

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

plot_ly(df, x = game, y = value, mode = "markers", color = season)
plot_ly(subset(df,season=="2001"), x = game, y = value, mode = "line")

Thanks in advance

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")

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")

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM