简体   繁体   English

如何在相同的图表图表上组合线条和散点图?

[英]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. 使用R plotly包创建时,从data.frame创建的两个单独的图表正常工作。
However, I am not sure how to combine them into one (presumably with the add_trace function) 但是,我不确定如何将它们组合成一个(大概是使用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")

Thanks in advance 提前致谢

The answer given by @LukeSingham does not work anymore with plotly 4.5.2 . @LukeSingham给出的答案不再适用于plotly 4.5.2 You have to start with an "empty" plot_ly() and then to add the traces: 您必须以“空” 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")

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). 有两种主要的方法你可以通过绘图,制作一个ggplot并转换为一个plotly对象,因为@MLavoie建议使用add_trace在现有的plotly对象上建议OR(见下文)。

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. 这是一种做你想要的方法,但是用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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