[英]ggplot2 density histogram with custom bin edges
I'm able to plot a density histogram, and I'm able to plot a regular histogram with custom bins, but not both together. 我能够绘制密度直方图,并且我能够绘制带有自定义分箱的常规直方图,但不能同时绘制两者。 Here's my attempt: 这是我的尝试:
library(ggplot2)
vals = c(2.6, 5.2, 4.1, 6.9, 5.7, 5.2, 4.4, 5.5, 6.3, 6.1, 4.7, 1.4)
myplot = qplot(vals, geom = 'blank') +
geom_line(aes(y = ..density..), stat = 'density',
colour = 26, size = 2, alpha = .6) +
geom_histogram(aes(y = ..density..), binwidth = 1,
fill = 28, alpha = 0.3) +
stat_bin(breaks=seq(-.5,8.5,1)) + xlim(-1, 9)
print(myplot)
If you remove the stat_bin
term, the histogram plots correctly as a density histogram, but with default bin locations. 如果删除stat_bin
术语,则直方图将正确绘制为密度直方图,但具有默认的bin位置。 Add the stat_bin
term, and the bins are correct but it's no longer a density histogram. 添加stat_bin
术语,并且二进制文件是正确的,但它不再是密度直方图。 Any ideas how to get both working? 任何想法如何让两个工作?
You can add argument breaks=
to the geom_histogram()
to set your own break points (you don't have to use geom_histogram()
and stat_bin()
together because geom_histogram()
uses stat_bin()
to produce result). 您可以将参数breaks=
添加到geom_histogram()
以设置自己的断点(您不必一起使用geom_histogram()
和stat_bin()
,因为geom_histogram()
使用stat_bin()
来生成结果)。
qplot(vals, geom = 'blank') +
geom_line(aes(y = ..density..), colour=26, stat = 'density', size = 2, alpha = .6) +
geom_histogram(aes(y = ..density..), fill = 28, alpha = 0.3, breaks=seq(-.5,8.5,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.