2012-09-12 3 views
11

私はgeom_density()が正確に何をしているのか知りたいので、グラフを正当化し、プロットされている各曲線に対して生成する関数や点を抽出する方法があれば正当化します。 get("compute_group", ggplot2::StatDensity)(または、以前、get("calculate", ggplot2:::StatDensity))を入力R - geom_density()はどのようなアルゴリズムを使い、ポイント/曲線の方程式を抽出するのですか?

おかげ

+0

私は(そのstat_densityを発見した)あなたはパラメータを設定することができます。だからおそらく最初の部分に答えます。それでも方程式や点を抽出できるかどうかを知りたい – unixsnob

答えて

18

はあなたの密度を計算するために使用されるアルゴリズムを取得します。 (。ルートで、それはkernel="gaussian"デフォルトでdensity()への呼び出しです)

プロットに使用されるポイントは、目に見えないprint.ggplot()によって返されるので、このようにそれらにアクセスすることができます。

library(ggplot2) 
m <- ggplot(movies, aes(x = rating)) 
m <- m + geom_density() 
p <- print(m) 
head(p$data[[1]], 3) 
#   y  x density scaled count PANEL group ymin  ymax 
# 1 0.0073761 1.0000 0.0073761 0.025917 433.63  1  1 0 0.0073761 
# 2 0.0076527 1.0176 0.0076527 0.026888 449.88  1  1 0 0.0076527 
# 3 0.0078726 1.0352 0.0078726 0.027661 462.81  1  1 0 0.0078726 


## Just to show that those are the points you are after, 
## extract and use them to create a lattice xyplot 
library(gridExtra) 
library(lattice) 
mm <- xyplot(y ~x, data=p$data[[1]], type="l") 

enter image description here

3

他の回答で示唆されているように、print.ggplot()を使用してgplotのポイントにアクセスできます。しかし、print() -ingコードはggplotオブジェクトも表示しますが、これは望ましくない場合があります。

あなたはggplot_build()を使用して、プロットを印刷することなく、ggplotオブジェクトデータを抽出し取得することができます。

library(ggplot2) 
library(ggplot2movies) 

m <- ggplot(movies, aes(x = rating)) 
m <- m + geom_density() 
p <- ggplot_build(m) # <---- INSTEAD OF `p <- print(m)` 
head(p$data[[1]], 3) 
#    y  x  density  scaled count  n PANEL group ymin 
# 1 0.007376115 1.000000 0.007376115 0.02591684 433.6271 58788  1 -1 0 
# 2 0.007652653 1.017613 0.007652653 0.02688849 449.8842 58788  1 -1 0 
# 3 0.007872571 1.035225 0.007872571 0.02766120 462.8127 58788  1 -1 0 


# Just to show that those are the points you are after, extract and use them 
# to create a lattice xyplot 
library(lattice) 
m2 <- xyplot(y ~x, data=p$data[[1]], type="l") 

library(gridExtra) 
grid.arrange(m, m2, nrow=1) 

enter image description here

+1

ありがとう、メガトロン、まさに私が探していたものです! – Luis

関連する問題