R - geom_density()使用什么算法以及如何提取曲线的点/方程?

uni*_*nob 13 r ggplot2

我想知道geom_density()究竟在做什么,所以我证明了图形的合理性,以及是否有任何方法可以提取为绘制的每条曲线生成的函数或点.

谢谢

Jos*_*ien 19

键入get("compute_group", ggplot2::StatDensity)(或以前get("calculate", ggplot2:::StatDensity))将为您提供用于计算密度的算法.(在根,这是一个呼叫density()kernel="gaussian"默认值).

绘图中使用的点是无形中返回的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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Meg*_*ron 6

根据其他答案的建议,您可以使用来访问ggplot点print.ggplot()。但是,print()-ing代码也会打印ggplot对象,这可能是不希望的。

你可以提取ggplot对象数据,而不打印的情节,使用ggplot_build()

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 谢谢,威震天,这正是我一直在寻找的! (2认同)