[英]how to plot step histograms in ggplot2 in R?
How can I plot a "step" or "staircase" histogram in ggplot2 in R? 如何在R中的ggplot2中绘制“阶跃”或“阶梯”直方图? something like: 就像是:
where width of each horizontal line represents the bin size (of the x-axis values) and the height corresponds to fraction of the data that falls in that bin (unlike the attached image where it is a probability density!). 其中每条水平线的宽度表示(大小为x轴值)的区域大小,高度对应于落入该区间的数据的分数 (与附加图像不同,它是概率密度!)。 is there a way to do this with geom_histogram
? 有没有办法用geom_histogram
做到这geom_histogram
?
Generate some data: 生成一些数据:
foo <- data.frame(bar=rnorm(100))
Histogram with step geom and counts on y-axis: 具有步进geom的直方图和y轴上的计数:
ggplot(foo,aes(x=bar)) + stat_bin(geom="step")
Histogram with step geom and density on y-axis: 在y轴上具有阶梯几何和密度的直方图:
ggplot(foo,aes(x=bar)) + stat_bin(aes(y=..density..),geom="step")
And with "fraction of data that falls into that bin": 并且“落入该垃圾箱的数据分数”:
ggplot(foo,aes(x=bar)) + stat_bin(aes(y=..count../sum(..count..)),geom="step")
Might be other, prettier ways to do this but here's one idea. 可能是其他更漂亮的方法,但这是一个想法。
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")
Edit: 编辑:
geom_histogram(size = 2, colour = "red", fill = "white")
creates this geom_histogram(size = 2, colour = "red", fill = "white")
创建了这个
I edited the thickness of the outline to size = 2
to make the final output look nice. 我将轮廓的粗细编辑为size = 2
,使最终输出看起来不错。 It looks awful at this stage. 在这个阶段看起来很糟糕。 To remove the interior lines you add geom_histogram(colour = "transparent", fill = "white")
which will draw another histogram on top covering the interior lines (and some of the outline which is why I think size = 2
looks nice) 要删除内部线条,请添加geom_histogram(colour = "transparent", fill = "white")
,这将在顶部绘制另一个直方图,覆盖内部线条(以及一些轮廓,这就是为什么我认为size = 2
看起来不错)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.