Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

ggplot2 - R - What algorithm does geom_density() use and how to extract points/equation of curves?

I would like to know what is geom_density() exactly doing, so I justify the graph and if there is any way of extracting the function or points that generates for each of the curves being plotted.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Typing get("compute_group", ggplot2::StatDensity) (or, formerly, get("calculate", ggplot2:::StatDensity)) will get you the algorithm used to calculate the density. (At root, it's a call to density() with kernel="gaussian" the default.)

The points used in the plot are invisibly returned by print.ggplot(), so you can access them like this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...