2012-10-13 20 views
3

語境: 我有一些數據,我想:添加任意函數的ggplot直方圖

  1. 情節他們的直方圖
  2. 增加一個內核密度
  3. 添加一個「理論密度「
  4. 添加圖例來區分2.和3之間

考慮:

X <- rnorm(1000,0,1) 
Y <- (X^2-1)/2 
ggplot(as.data.frame(Y), aes(x=Y)) + 
    geom_histogram(aes(y=..density..),  
        binwidth=.2, 
        colour="black", fill="white") + 
    geom_density(alpha=.2, fill="#FF6666") 

enter image description here

這完成1和2,但我怎麼能實現3和4?我已經寫了我要繪製函數:

myfunc <- function(x) { 
    2*exp(-x-0.5)/(sqrt(2*x+1)*sqrt(2*pi)) 
} 

其他任何評論/批評歡迎(我學習)

+1

對於(3)查看'stat_function',雖然圖例可能需要計算ggplot以外的兩條線並手動添加一個geom_path層,這取決於您對圖例外觀的挑剔程度。 – joran

回答

4

您的自定義功能是不是非常不乖上域,所以我取代另一個爲了說明的目的,簡單的一個。

#Dummy data set for the legend 
dat <- data.frame(x = rep(NA_integer_,2), 
        y = rep(NA_integer_,2), 
        grp = c('Theoretical','Estimated')) 
ggplot(as.data.frame(Y), aes(x=Y)) + 
    geom_histogram(aes(y=..density..),  
        binwidth=.2, 
        colour="black", fill="white") + 
    geom_density(alpha=.2, fill="#FF6666",color = '#FF6666') + 
    stat_function(fun = function(x) exp(-x),colour = "blue") + 
    geom_point(data = dat,aes(x = x,y = y,color = grp)) + 
    scale_color_manual(name = "",values = c('#FF6666','blue')) 

enter image description here

我與顏色monkeyed一些,但你也可以自行調整,你認爲合適。可能有一種更清晰的方式來做圖例,但「NA和分組變量的數據框」是我對這種事情的標準方法。

+0

太好了。感謝+1 –