Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R extract coordinates plotted by ggplot2::stat_density_2d

Tags:

r

ggplot2

I am looking for the coordinates of contour lines produced by ggplot2::geom_density_2d.

I am after a list of (matrices of) x/y coordinates. One for each contour line.

This should be similar to what contourLines gives, but I was unable to get the desired result.

Here is some sample code from ?stat_density2d

 m <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
  geom_point() +
  xlim(0.5, 6) +
  ylim(40, 110)
 m + geom_density_2d()
like image 337
Andreas Avatar asked Feb 08 '23 10:02

Andreas


1 Answers

You can use ggplot_build:

ggplot_build(m + stat_density2d())$data[[2]]

  level        x        y piece  group PANEL  colour size linetype alpha
1 0.002 1.633788 40.00000     1 -1-001     1 #3366FF  0.5        1    NA
2 0.002 1.611111 40.11723     1 -1-001     1 #3366FF  0.5        1    NA
3 0.002 1.555556 40.47552     1 -1-001     1 #3366FF  0.5        1    NA
4 0.002 1.526300 40.70707     1 -1-001     1 #3366FF  0.5        1    NA
5 0.002 1.500000 40.91549     1 -1-001     1 #3366FF  0.5        1    NA
6 0.002 1.448020 41.41414     1 -1-001     1 #3366FF  0.5        1    NA
...
like image 115
erc Avatar answered Feb 10 '23 00:02

erc