如何使用类似于直方图的密度图的曲线拟合条形图?
library(ggplot2)
library(plyr)
y<-hist(rnorm(1000),breaks=30)$count
df<-data.frame(x=1:length(y),y=y,key="A")
df2<-data.frame(x=1:length(y),y=y*0.4,key="B")
df<-rbind(df,df2)
p<-ggplot(df,aes(x=x))
p<-p + geom_bar(subset=.(key =="A"),aes(y = y),stat="identity",fill = "blue", alpha = 0.2)
p<-p + geom_bar(subset=.(key =="B"),aes(y = y),stat="identity",fill = "blue", alpha = 0.2)
#p<-p + geom_density(subset=.(key =="A"), aes(y=y),alpha=.2, fill="#0000FF")
p
答案 0 :(得分:0)
使用 .. density .. 进行转换:
data = data.frame(x = rnorm(500))
ggplot(data) +
geom_histogram(aes(x = x, y = ..density..)) +
geom_density(aes(x), colour = I('red'))
对于您的数据:
ggplot(df) +
geom_histogram(aes(y, ..density.., fill=key)) +
geom_density(aes(y, colour = key))
尽量避免像'df'这样的名字(df是我猜的R函数)