【问题标题】:Generate a Filled geom_step生成填充的 geom_step
【发布时间】:2014-02-19 16:54:42
【问题描述】:

我可以用geom_ribbongeom_area 得到一个“填充”geom_linegeom_step 是否有不需要弄乱多边形/条形图或创建实际步进点的等价物?以下是一些示例数据:

library(ggplot2)
set.seed(1)
df <- data.frame(
  x=rep(sort(sample(1:20, 5)), 3), 
  y=ave(runif(15), rep(1:3, each=5), FUN=cumsum),
  grp=letters[rep(1:3, each=5)]
)
ggplot(df, aes(x=x, y=y, color=grp)) + geom_step(position="stack")

产生:

基本上,我想要完全相同的东西,但有填充区域。我知道如何通过实际创建步骤所需的 x/y 值并使用geom_area 来做到这一点,但我希望有更简单的方法。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

这是我正在考虑的答案,供参考,但我希望尽可能简单/内置:

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

【讨论】:

    【解决方案2】:

    我知道这个问题已经有几年了,但我今天遇到了同样的问题。供参考,这是我的解决方案。它并不比原始答案更简洁,但对某些人来说可能更容易理解。

    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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2023-01-23
      • 2014-05-05
      相关资源
      最近更新 更多