生成填充的geom_step [英] Generate a Filled geom_step

查看:141
本文介绍了生成填充的geom_step的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过 geom_ribbon geom_area 来获得填充 geom_line code>。是否有一个与 geom_step 不等同的多边形/条形图或创建实际步骤点?以下是一些示例数据:

I can get a "filled" geom_line with either geom_ribbon or geom_area. Is there an equivalent for geom_step that doesn't require messing with polygons/barplots or creating the actual step points? Here is some sample data:

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 来做到这一点,但我希望有更简单的方法。

Basically, I want exactly the same thing, but with filled areas. I know how to do this by actually creating the x/y values required for the steps and using geom_area, but I'm hoping there is something simpler.

推荐答案

以下是我想到的答案,供参考,但我希望如果可能,请尽量简化/内置:

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

这篇关于生成填充的geom_step的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆