ggplot在ggplot上的点之上绘制2d概率密度函数

时间:2017-10-07 15:59:54

标签: r ggplot2

我有以下示例:

require(mvtnorm)
require(ggplot2)
set.seed(1234)
xx <- data.frame(rmvt(100, df = c(13, 13)))
ggplot(data = xx,  aes(x = X1, y= X2)) + geom_point() + geom_density2d()

以下是我得到的内容:enter image description here

但是,我想从dmvt函数给出的mutlivariate t密度得到密度等值线。我如何调整geom_density2d来做到这一点?

1 个答案:

答案 0 :(得分:0)

这不是一个容易回答的问题:因为需要计算轮廓并使用椭圆包绘制椭圆。

使用椭圆t密度来更好地说明绘图。

nu <- 5  ## this is the degrees of freedom of the multivariate t. 

library(mvtnorm) 
library(ggplot2)

sig <- matrix(c(1, 0.5, 0.5, 1), ncol = 2)  ## this is the sigma parameter for the multivariate t

xx <- data.frame( rmvt(n = 100, df = c(nu, nu), sigma = sig)) ## generating the original sample

rtsq <- rowSums(x = matrix(rt(n = 2e6, df = nu)^2, ncol = 2)) ## generating the sample for the ellipse-quantiles. Note that this is a cumbersome calculation because it is the sum of two independent t-squared random variables with the same degrees of freedom so I am using simulation to get the quantiles. This is the sample from which I will create the quantiles.

g <- ggplot( data = xx
         ,  aes( x = X1
              , y = X2
                )
           ) + geom_point(colour = "red", size = 2)      ## initial setup

library(ellipse)

for (i in seq(from = 0.01, to = 0.99, length.out = 20)) {
    el.df <- data.frame(ellipse(x = sig, t = sqrt(quantile(rtsq, probs = i))))    ## create the data for the given quantile of the ellipse.
    names(el.df) <- c("x", "y")
    g <- g + geom_polygon(data=el.df, aes(x=x, y=y), fill = NA, linetype=1, colour = "blue") ## plot the ellipse
}

g + theme_bw() 

这会产生: enter image description here

我还有一个问题:如何减小绘图椭圆线的大小?