Generate a Filled geom_step

前端 未结 2 334
[愿得一人]
[愿得一人] 2020-12-28 19:40

I can get a \"filled\" geom_line with either geom_ribbon or geom_area. Is there an equivalent for geom_step that doesn\'

相关标签:
2条回答
  • 2020-12-28 20:34

    I know the question is a few years old, but I had the same problem today. For reference here's my solution. It's not more concise than the original answer, but may be easier to understand for some.

    library(ggplot2)
    library(dplyr)
    
    df <- data.frame(x = seq(10), y = sample(10))
    
    df_areaStep <- bind_rows(old = df, 
                             new = df %>% mutate(y = lag(y)),
                             .id = "source") %>%
                   arrange(x, source)
    
    ggplot(df, aes(x,y)) + 
      geom_ribbon(aes(x = x, ymin = 0, ymax = y), data = df_areaStep)
    

    See this gist for longer version with comments.

    0 讨论(0)
  • 2020-12-28 20:43

    Here is the answer I was thinking of, for reference, but I'm hoping for something simpler/built-in if possible:

    df2 <- rbind(
      df,
      transform(df[order(df$x),],
        x=x - 1e-9,  # required to avoid crazy steps
        y=ave(y, grp, FUN=function(z) c(z[[1]], head(z, -1L)))
    ) )
    ggplot(df2, aes(x=x, y=y, fill=grp)) + geom_area()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题