如何在R中使用ggplot2绘制阶梯状直方图?

11
我该如何在R中用ggplot2绘制“阶梯式”直方图?类似于下面的图片: enter image description here 每条水平线的宽度表示x轴值的区间宽度,高度表示该区间内数据的占比(注意不是概率密度,而是占比)。是否可以使用geom_histogram来实现这个效果?
2个回答

15

使用 geom_step

生成一些数据:

foo <- data.frame(bar=rnorm(100))

使用分步几何和y轴计数的直方图:

ggplot(foo,aes(x=bar)) + stat_bin(geom="step")

使用步幅几何图形和密度函数表示的直方图,y轴表示密度:

ggplot(foo,aes(x=bar)) + stat_bin(aes(y=..density..),geom="step")

并且涉及到“落入该区间的数据部分”:

ggplot(foo,aes(x=bar)) + stat_bin(aes(y=..count../sum(..count..)),geom="step")

在此输入图像描述


3
也许还有其他更漂亮的方法,但这里有一个想法。
foo <- data.frame(bar = rnorm(100)) + theme_bw()
p <- ggplot(data = foo, aes(x = bar, y = ..count../sum(..count..))) ## or aes(x = bar, y = ..density..) if you want that
p + geom_histogram(size = 2, colour = "red", fill = "white") + geom_histogram(colour = "transparent", fill = "white")

enter image description here

编辑:

geom_histogram(size = 2, colour = "red", fill = "white") 创建了以下内容:enter image description here

我将轮廓线的宽度编辑为size = 2,以使最终输出结果更美观。但在这个阶段看起来很糟糕。为了移除内部线条,您可以添加geom_histogram(colour = "transparent", fill = "white"),这会在顶部绘制另一个直方图,覆盖内部线条(以及一些轮廓线,这就是我认为size = 2看起来不错的原因)。


@user248237dfsf 只需删除第二个并观察发生了什么。 这应该是显而易见的。 - Roland
@user248237dfsf,ziggystar的回答更好,可以更轻松地使用颜色并在同一图中绘制多个。听起来这是您的最终目标。 - Jake Burkhead
@JakeBurkhead:同意,但是当我尝试使用多种颜色的解决方案时,直方图仍然会相互遮挡,看起来不好。geom_density可以正确地得到多条彩色线,但形状不对,所以不确定答案是什么。 - user248237
@user248237dfsf 谁在使用geom_density?我的解决方案使用了geom_step(这正是你所要求的),而Jake的解决方案则使用了geom_histogram - ziggystar
@ziggystar:我正在将geom_density与您的解决方案进行对比。当我尝试使用多种颜色运行您的解决方案时,线条会彼此遮挡。 - user248237
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接