pssguy pssguy - 1 year ago 76
R Question

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.

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

Answer Source

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


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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download