覆盖直方图与密度曲线 [英] Overlay histogram with density curve
问题描述
我试图制作密度值的直方图,并用密度函数的曲线(而不是密度估计值)叠加。使用简单的标准法线例如,以下是一些数据:
pre code $ x< - rnorm(1000)
我可以这样做:
q < - qplot(x,geom =直方图)
q + stat_function(fun = dnorm)
但是这给出了频率的直方图的比例而不是密度。 .. density ..
我可以在直方图上得到合适的比例:
q < - qplot(x,.. density ..,geom =直方图)
q
但现在这给出一个错误:
q + stat_function(fun = dnorm)
有没有我没有看到的东西?
另一个问题,有没有办法绘制一个函数的曲线,比如 curve()
,但是不能作为图层?
#创建一些数据与
x一起使用= rnorm(1000);
#覆盖直方图,经验密度和法线密度
p0 = qplot(x,geom ='blank')+
geom_line(aes(y = ..density .., color ='Empirical'),stat ='density')+
stat_function(fun = dnorm,aes(color ='Normal'))+
geom_histogram(aes(y = ..density ..) ,alpha = 0.4)+
scale_colour_manual(name ='Density',values = c('red','blue'))+
theme(legend.position = c(0.85,0.85))
print(p0)
I am trying to make a histogram of density values and overlay that with the curve of a density function (not the density estimate).
Using a simple standard normal example, here is some data:
x <- rnorm(1000)
I can do:
q <- qplot( x, geom="histogram")
q + stat_function( fun = dnorm )
but this gives the scale of the histogram in frequencies and not densities. with ..density..
I can get the proper scale on the histogram:
q <- qplot( x,..density.., geom="histogram")
q
But now this gives an error:
q + stat_function( fun = dnorm )
Is there something I am not seeing?
Another question, is there a way to plot the curve of a function, like curve()
, but then not as layer?
Here you go!
# create some data to work with
x = rnorm(1000);
# overlay histogram, empirical density and normal density
p0 = qplot(x, geom = 'blank') +
geom_line(aes(y = ..density.., colour = 'Empirical'), stat = 'density') +
stat_function(fun = dnorm, aes(colour = 'Normal')) +
geom_histogram(aes(y = ..density..), alpha = 0.4) +
scale_colour_manual(name = 'Density', values = c('red', 'blue')) +
theme(legend.position = c(0.85, 0.85))
print(p0)
这篇关于覆盖直方图与密度曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!