如何在同一个图表上组合一条线和散点图?
How can I combine a line and scatter on same plotly chart?
从 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")
提前致谢
这里有一种方法可以做你想做的事,但是使用 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))
有两种主要的方法可以用 plotly 做到这一点,制作一个 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")
@LukeSingham 给出的答案不再适用于 plotly 4.5.2
。
您必须从 "empty" 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")
从 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")
提前致谢
这里有一种方法可以做你想做的事,但是使用 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))
有两种主要的方法可以用 plotly 做到这一点,制作一个 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")
@LukeSingham 给出的答案不再适用于 plotly 4.5.2
。
您必须从 "empty" 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")