问题描述
我怎样才能制作一个柱状图,其中所有的柱状图加起来都是1,并在上面加上一个密度层?
set.seed(1234)
df< - data.frame(
sex = factor(rep每个= 200),
weight = round(c(rnorm(200,mean = 55,sd = 5),
rnorm(200,mean = 65,sd = 5)))
)
图书馆(ggplot2)
ggplot(df,aes(x =重量,颜色=性别,填充=性别))+
geom_histogram(aes(y = .. density ../ sum(.. density ..)),alpha = 0.5,
position =identity)+
geom_density( alpha = .2)
How can I make a histogram in which all bars add up to 1 and add a density layer above that fits?
set.seed(1234) df <- data.frame( sex=factor(rep(c("F", "M"), each=200)), weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5))) )(taken from: http://www.sthda.com/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization )
ggplot(df, aes(x=weight, color=sex, fill=sex)) + geom_histogram(aes(y=..density..), alpha=0.5, position="identity")+ geom_density(alpha=.2)but when I change aes(y=..density..) to aes(y=..scaled..) I get an error.
If I use this example with my (big) data the density goes up to 120.So basically this:![bar]http://www.sthda.com/sthda/RDoc/figure/easy-ggplot2/ggplot2-histogram-multiple-groups3.pngwith a different y-axis. (so that all bars of one type add up to 1)
I am not sure if it is statistically legit to use geom_smooth?
解决方案Try using y = ..density../sum(..density..):
set.seed(1234) df <- data.frame( sex=factor(rep(c("F", "M"), each=200)), weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5))) ) library(ggplot2) ggplot(df, aes(x=weight, color=sex, fill=sex)) + geom_histogram(aes(y=..density../sum(..density..)), alpha=0.5, position="identity")+ geom_density(alpha=.2)
这篇关于ggplot2 geom_density和geom_histrogram在一个绘图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!