如何使用带有geom =“ line”的stat_summary在ggplot2中绘制NA间隙?

mav*_*cks 5 r ggplot2

如何绘制数据包含NA的是“空白”,在stat_summarygeom = "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)

geom_line

    # 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)

geom_path

    # 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)

stat_summary_with_line

非常感谢您的帮助!

d.b*_*d.b 2

您可以添加一列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)