【问题标题】:ggplot plot 2d probability density function on top of points on ggplotggplot 在 ggplot 上的点上绘制 2d 概率密度函数
【发布时间】:2017-10-17 21:23:02
【问题描述】:

我有以下例子:

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()

这是我得到的:

但是,我想从 dmvt 函数给出的多变量 t 密度中获得密度等高线。我如何调整 geom_density2d 来做到这一点?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    使用椭圆 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() 
    

    这会产生:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-23
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多