Reputation: 7846
ggplot allows me to plot contour lines for a data series x and y:
library(ggplot2)
df <- data.frame(x=c(1:100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_density2d()
I would like to be able to save the data output of the main four contour lines (95,75,50,25)max and (95,75,50,25)min in a dataframe. I would be grateful for your help. Perhaps there is a way of doing this directly, without using ggplot.
Upvotes: 2
Views: 541
Reputation: 98509
Using function ggplot_build(
) around ggplot()
object you can access all data used for the plotting. Data are stored in list element data
.
p<-ggplot_build(ggplot(df,aes(x=x,y=y))+geom_density2d())
str(p$data)
List of 1
$ :'data.frame': 1895 obs. of 6 variables:
..$ level: num [1:1895] 5e-04 5e-04 5e-04 5e-04 5e-04 5e-04 5e-04 5e-04 5e-04 5e-04 ...
..$ x : num [1:1895] 1 2 3 4 5 ...
..$ y : num [1:1895] 1.42 1.44 1.45 1.45 1.46 ...
..$ piece: int [1:1895] 1 1 1 1 1 1 1 1 1 1 ...
..$ group: Factor w/ 13 levels "1-001","1-002",..: 1 1 1 1 1 1 1 1 1 1 ...
..$ PANEL: int [1:1895] 1 1 1 1 1 1 1 1 1 1 ...
You can store those data as separate data frame.
gg<-p$data[[1]]
head(gg)
level x y piece group PANEL
1 5e-04 1.000000 1.423926 1 1-001 1
2 5e-04 2.000000 1.435286 1 1-001 1
3 5e-04 3.000000 1.445293 1 1-001 1
4 5e-04 4.000000 1.454166 1 1-001 1
5 5e-04 5.000000 1.462106 1 1-001 1
6 5e-04 5.255343 1.463967 1 1-001 1
group
and piece
variables shows for which line each value belong (1 - outer lines, 13 - inner lines in this case).
Upvotes: 5