Can you extract data points from cluster levels in ggplot::geom_density_2d_filled?

Viewed 48

For my data, each patient has numeric data from 2 samples, which I've plotted as individual coordinates for each patient and used ggplot::geom_density_2d_filled to visualize clusters.

Ultimately, I have many more sample pairs for the same patients which I'm visualizing the same way, and I want to see if certain patients are always clustered near each other. However, I can't find a way to extract the specific points (with their associated patient ID) that fall within each specific level/ cluster of the plot. Is there any way to do this? Should I be using a different approach not involving ggplot::geom_density_2d_filled?

Edit: Here's a preview of my data and the code I used to generate the graphs

   patient_ID pLPE_18.0 Cl_total_18.0
1      993397 1796.4549     0.9379375
2      993398 1991.2818     0.5847325
3      993477 2638.1399     1.3453963
4      993480 3366.4634     2.2080976
5      993481 1778.2783     1.3255837
6      993490 2409.2275     1.2605374
st1 <- ggplot(PC_16_mod, aes(x=Cl_total_18.0, y=pLPE_18.0, label=patient_ID)) +
  geom_point(size=0.5, shape=16)
st1 + geom_density_2d_filled(alpha = 0.5) 

The actual data set I have has each column as a different sample type, but I'm just showing 2 since I'm analyzing them 2 at a time, if that makes sense

1 Answers

You can use ggplot_build, but as other commenters mentioned, there may be better ways to get this information.

st1 <- ggplot(dt1, aes(Cl_total_18.0, pLPE_18.0, label = patient_ID)) +
  geom_point(size=0.5, shape=16) +
  geom_density_2d_filled(alpha = 0.5) 

dt2 <- ggplot_build(st1)$data[[2]]
summary(dt2 %>% mutate_if(is.character, as.factor))

head(dt2)
       fill          level        x        y piece  group subgroup level_low
1 #440154FF (0e+00, 1e-04] 1.920662 3366.463     1 -1-001        1         0
2 #440154FF (0e+00, 1e-04] 1.912940 3366.463     1 -1-001        1         0
3 #440154FF (0e+00, 1e-04] 1.896543 3366.463     1 -1-001        1         0
4 #440154FF (0e+00, 1e-04] 1.880145 3366.463     1 -1-001        1         0
5 #440154FF (0e+00, 1e-04] 1.863747 3366.463     1 -1-001        1         0
6 #440154FF (0e+00, 1e-04] 1.847350 3366.463     1 -1-001        1         0
  level_high level_mid nlevel n PANEL colour size linetype alpha
1      1e-04     5e-05  0.125 6     1     NA  0.5        1   0.5
2      1e-04     5e-05  0.125 6     1     NA  0.5        1   0.5
3      1e-04     5e-05  0.125 6     1     NA  0.5        1   0.5
4      1e-04     5e-05  0.125 6     1     NA  0.5        1   0.5
5      1e-04     5e-05  0.125 6     1     NA  0.5        1   0.5
6      1e-04     5e-05  0.125 6     1     NA  0.5        1   0.5

enter image description here

Related