2
votes

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

3

3 Answers

10
votes

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

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

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