用密度曲线叠加直方图 [英] Overlay histogram with density curve

查看:38
本文介绍了用密度曲线叠加直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作密度值的直方图,并将其与密度函数的曲线(不是密度估计值)叠加.

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)

我能做到:

q <- qplot( x, geom="histogram")
q + stat_function( fun = dnorm )

但这给出了直方图的频率而不是密度的比例.使用 ..density.. 我可以在直方图上获得适当的比例:

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?

另一个问题,有没有办法绘制函数的曲线,比如curve(),但不是作为层?

Another question, is there a way to plot the curve of a function, like curve(), but then not as layer?

推荐答案

给你!

# 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆