2016-03-24 34 views
4

我的目標是能夠使用geom_density2d()幾何在用戶定義位置的散點圖上繪製輪廓線。請看下面的代碼:具有特定輪廓的geom_statdensity2d?

library(ggplot2) 
n = 100 
df = data.frame(x = c(rnorm(n, 0, .5), rnorm(n, 3, .5)), 
       y = c(rnorm(n, 1, .5), rnorm(n, 0, .5))) 

ggplot(df, aes(x = x, y = y)) + 
    geom_density2d() + 
    geom_point() 

enter image description here

這將產生一個標準的等高線圖,但似乎沒有成爲一個方式來手動控制其形狀部拿得出。可選參數bin和h in可以在一定程度上控制輪廓線(從我假設的MASS傳遞給kde2d),但生成的線似乎不可解釋。

理想情況下,我可以從ks庫中複製plot.kde的功能,通過該參數可以控制這些功能。

library(ks) 
est = kde(df) 
plot(est, cont = c(50, 95)) 

enter image description here

+0

也許,這是有幫助的:http://stackoverflow.com/questions/23437000/how-to-plot-a-contour-line-showing-where-95-of-values-水落內,在-R和在 – Jimbou

回答

0

這是我天真的嘗試,因爲我幾乎沒有編寫自定義的功能。所以以下可能不是一個好方法。但至少,代碼完成了這項工作。我的竅門是使用ggplot創建的數據集。首先,繪製圖形並獲取用於圖形的數據,您可以從ggplot_build(g)$data[1]中找到這些數據。在這裏,你可以找到一個名爲level的列。使用該列,可以爲每個輪廓線子集數據。在myfun()中,您需要指定您想要的級別。該函數將指定級別的數據分組並繪製一個圖形。

setseed(111) 
mydf = data.frame(x = c(rnorm(100, 0, .5), rnorm(100, 3, .5)), 
        y = c(rnorm(100, 1, .5), rnorm(100, 0, .5))) 

g <- ggplot(mydf, aes(x = x, y = y)) + 
      geom_density2d() + 
      geom_point() 

### Get a list containing data used for drawing g. 

temp <- as.data.frame(ggplot_build(g)$data[1]) 

### Check which levels you have in g 

ind <- unique(temp$level) 

ind 
#[1] 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20 


myfun <- function(...){ 
       ana <- c(...) 
       foo <- subset(temp, level %in% ana) 

       g <- ggplot() + 
       geom_path(data = foo, aes(x = x, y = y, group = group), colour = "red") 

       print(g) 

       } 

### Run myfun by specify levels you want. 
myfun(0.02, 0.10, 0.18) 

enter image description here