2

从 data.frame 创建的两个单独的图表在使用 R plotly 包创建时可以正常工作。
但是,我不确定如何将它们组合成一个(大概是使用 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")

提前致谢

4

3 回答 3

10

@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")
于 2016-10-30T21:52:50.793 回答
4

这是一种做你想做的事情的方法,但是使用 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))
于 2015-12-23T23:01:31.227 回答
4

有两种主要方法可以使用 plotly 执行此操作,按照@MLavoie 的建议,制作 aggplot并转换为plotly对象,或者您怀疑通过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")
于 2015-12-23T23:01:47.070 回答