OpenSauce
OpenSauce

Reputation: 354

Is there a way to convert the plot derived from Spatstat's K function into a ggplot or grob?

I am trying to use ggarrange from ggpubr to create a multiple plot of Ripley's K function from spatstat, i.e. I calculate Ripley's K using Kest() for 5 landscapes and then plot them all together. Such as:

kk1plot<-plot(Kest(landscape))

However I am returning the error "Cannot convert object of class data.frame into a grob" when I try to use:

k1<-ggarrange(kk1plot,kk2plot,kk3plot,kk4plot,kk5plot,nrow=3,ncol=2) 

Similarly I return the error "Only know how to add ggplots and/or grobs" when I use patchwork and the code:

k1<-wrap_plots(list(kk1plot,kk2plot,kk3plot,kk4plot,kk5plot),nrow=3,ncol=2)

Would anyone know how I could plot the output of multiple Ripley's K function as a single plot? i.e. convert the output of spatstat's Kest() into a plot that can be manipulated using one of the above lines of code?

Upvotes: 1

Views: 586

Answers (2)

Ege Rubak
Ege Rubak

Reputation: 4507

The spatstat package uses base graphics. The built-in way to plot multiple estimated K-functions would be something along the lines below. The returned output from Kest is a data.frame with the different estimates as columns so you can plot it using ggplot by using the relevant aesthetics yourself.

library(spatstat)
X1 <- rpoispp(100)
X2 <- rpoispp(100)
X3 <- rpoispp(100)
X4 <- rpoispp(100)
X5 <- rpoispp(100)
Xlist <- solist(X1, X2, X3, X4, X5)
plot(Xlist, main = "", main.panel = "")

Klist <- lapply(Xlist, Kest)
Klist <- as.anylist(Klist)
plot(Klist, main = "", main.panel = "")

Upvotes: 5

Ian Campbell
Ian Campbell

Reputation: 24770

One approach is to use ggplotify::as.grob to capture the plot as a grob object.

You can then plot that using ggpubr::ggarange.

The proper syntax is as.grob(~ ...) replacing ... with the plot function.

library(ggplotify)
library(ggpubr)
library(spatstat)
for(i in 1:5){
  varname <- paste0("kk",i,"plot")
  assign(varname,
         as.grob(~plot(Kest(rMatClust(kappa=5,r=0.1,mu=100)),
                       main = paste("Plot",i),
                       cex.axis = 0.5, cex.main = 0.6,
                       legendargs = list(cex = 0.2)))
  )
}
ggarrange(kk1plot,kk2plot,kk3plot,kk4plot,kk5plot,nrow=3,ncol=2) 

enter image description here

Upvotes: 3

Related Questions