使用R plotly包创建时,从data.frame创建的两个单独的图表正常工作 然而, 我不知道如何将它们组合成一个(大概是使用add_trace函数)
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")
提前致谢
答案 0 :(得分:9)
@LukeSingham给出的答案不再适用plotly 4.5.2
。
您必须以“空”plot_ly()
开头,然后添加跟踪:
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")
答案 1 :(得分:4)
有两种主要方法可以通过绘图实现这一点,制作ggplot
并转换为plotly
对象,因为@MLavoie建议您使用add_trace
对现有内容进行操作plotly
对象(见下文)。
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")
答案 2 :(得分:3)
这是一种做你想要的方法,但是使用ggplot2 :-)你可以根据需要改变背景,线条,点颜色。
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))