如何绘制数据包含NA的是“空白”,在stat_summary用geom = "line"?
代替geom_line()使用是可行的geom_path()(请参阅如何使用ggplot2绘制NA间隙以及如何在geom_line 中绘制包含NA的数据作为“间隙”)。
MWE建立在@stuttungr的示例上(从此处开始)
df = data.frame( x = c(1:10), y = c(1:10) )
df[5:7, ]=NA
# get NO gap as expected
ggplot(data=df, aes(x,y)) +
geom_point(color = "green", size = 5) +
geom_line()
Run Code Online (Sandbox Code Playgroud)
# get the gap as expected
ggplot(data=df, aes(x,y)) +
geom_point(color = "green", size = 5) +
geom_path()
Run Code Online (Sandbox Code Playgroud)
# get NO gap unfortunately
ggplot(data=df, aes(x,y)) +
geom_point(color = "orange", size = 5) +
stat_summary(fun.y = mean, geom = "line")
Run Code Online (Sandbox Code Playgroud)
非常感谢您的帮助!
您可以添加一列group
ggplot(data = transform(df, group = with(rle(is.na(df$x)), rep(seq_along(values), lengths))),
aes(x, y, group = group)) +
geom_point(color = "orange", size = 5) +
stat_summary(fun.y = mean, geom = "line")
Run Code Online (Sandbox Code Playgroud)
这是data
transform(df, group = with(rle(is.na(df$x)), rep(seq_along(values), lengths)))
# x y group
#1 1 1 1
#2 2 2 1
#3 3 3 1
#4 4 4 1
#5 NA NA 2
#6 NA NA 2
#7 NA NA 2
#8 8 8 3
#9 9 9 3
#10 10 10 3
Run Code Online (Sandbox Code Playgroud)