生成填充的geom_step

Bro*_*ieG 9 r ggplot2

我可以得到一个"装" geom_line与任一geom_ribbongeom_area.是否有相应的geom_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")
Run Code Online (Sandbox Code Playgroud)

哪个产生:

在此输入图像描述

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

Tob*_*otz 8

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

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)
Run Code Online (Sandbox Code Playgroud)

有关更长版本的注释,请参阅此要点。


Bro*_*ieG 6

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

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述