2016-01-21 102 views
1

我最近遇到了ggplot2 :: geom_density問題,我無法解決。我試圖將某些變量的密度可視化並將其與常量進行比較。爲了繪製密度,我使用了ggplot2 :: geom_density。爲此我繪製的密度變量,但恰好是一個常數(這個時候):R ggplot2 :: geom_density與一個常量變量

df <- data.frame(matrix(1,ncol = 1, nrow = 100)) 
colnames(df) <- "dummy" 

dfV <- data.frame(matrix(5,ncol = 1, nrow = 1)) 
colnames(dfV) <- "latent" 

ggplot() + 
    geom_density(data = df, aes(x = dummy, colour = 's'), 
       fill = '#FF6666', alpha = 0.2, position = "identity") + 
    geom_vline(data = dfV, aes(xintercept = latent, color = 'ls'), size = 2) 

enter image description here 這是確定,這是我所期望的。但是,當我這個分佈轉移到最右邊,我得到一個情節是這樣的:

df <- data.frame(matrix(71,ncol = 1, nrow = 100)) 
colnames(df) <- "dummy" 

dfV <- data.frame(matrix(75,ncol = 1, nrow = 1)) 
colnames(dfV) <- "latent" 

ggplot() + 
    geom_density(data = df, aes(x = dummy, colour = 's'), 
       fill = '#FF6666', alpha = 0.2, position = "identity") + 
    geom_vline(data = dfV, aes(xintercept = latent, color = 'ls'), size = 2) 

enter image description here 這可能意味着內核估計仍然以0作爲配送中心(吧?)。

有什麼辦法可以繞過這個嗎?我希望看到類似上面的情節,只有克納密度的中心將在71和75中

感謝

+0

它與通過'ggplot2 :: stat_density'傳遞給'stat :: density'的調整和bw參數有關。我不確定如何修改它以獲得您想要的解決方案......雖然當然,做一個常數的密度估計是愚蠢的 –

+0

嗯?這有幫助嗎? –

回答

0

好吧,我不知道該代碼所做的V線,但我懷疑geom_density基元不是針對值完全相同的情況而設計的,並且它正在對分配進行一些假設,而這些假設並不符合您的期望。下面是一些代碼和劇情有帶來了曙光:

# Generate 10 data sets with 100 constant values from 0 to 90 
# and then merge them into a single dataframe 

dfs <- list() 
for (i in 1:10){ 
    v <- 10*(i-1) 
    dfs[[i]] <- data.frame(dummy=rep(v,100),facet=v) 
} 
df <- do.call(rbind,dfs) 

# facet plot them 
ggplot() + 
    geom_density(data = df, aes(x = dummy, colour = 's'), 
         fill = '#FF6666', alpha = 0.5, position = "identity") + 
    facet_wrap(~ facet,ncol=5) 

產量:

enter image description here

所以它沒有做什麼你認爲它是,但它也可能不是做什麼你想。你當然可以使其「翻譯不變」(幾乎)加入一些噪音像這樣的例子:

set.seed(1234) 

noise <- +rnorm(100,0,1e-3) 
dfs <- list() 
for (i in 1:10){ 
    v <- 10*(i-1) 
    dfs[[i]] <- data.frame(dummy=rep(v,100)+noise,facet=v) 
} 
df <- do.call(rbind,dfs) 

ggplot() + 
    geom_density(data = df, aes(x = dummy, colour = 's'), 
       fill = '#FF6666', alpha = 0.5, position = "identity") + 
    facet_wrap(~ facet,ncol=5) 

產量:

enter image description here

注意,顯然有一個隨機的成分geom_density函數,並且我無法看到如何在每個實例之前設置種子,因此每次估計的密度都有點不同。