简体   繁体   中英

How to plot NA gaps in ggplot2 using stat_summary with geom = "line"?

How to plot data containing NAs as "gaps" in stat_summary with geom = "line" ?

It is feasible for geom_line() by using geom_path() instead (see how to plot NA gaps using ggplot2 and How to plot data containing NA's as "gaps" in geom_line ).

MWE building on the example from @stuttungr (from here )

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

geom_line

    # get the gap as expected
    ggplot(data=df, aes(x,y)) +
      geom_point(color = "green", size = 5) +
      geom_path()

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

stat_summary_with_line

Many thanks for any help!

You could add a column for 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")

在此处输入图片说明

Here's the 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

data.table::rleid is convenient for these cases :

ggplot(df, aes(x, y, group=data.table::rleid(is.na(x)))) +
  geom_point(color = "orange", size = 5) +
  stat_summary(fun.y = mean, geom = "line")
#> Warning: Removed 3 rows containing non-finite values (stat_summary).
#> Warning: Removed 3 rows containing missing values (geom_point).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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