Skip to content
Prev 28980 / 29559 Next

Need to plot all 5 spatial maps together in a single window

On Thu, 9 Jun 2022, J. Marius RAKOTONDRAMANGA wrote:

            
Marius,

Thanks for trying to help, but cowplot is designed to combine plots 
created using grid, not base, graphics. To use it (or gridExtra), sf 
plots, which are base graphics, must be converted to grid objects (grobs), 
for example using the gridGraphics package.

Since Ranjeet did not provide a reproducible example, this may not 
correspond well, but given the lack of information, it's hard to be more 
precise:

library(sf)
nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"))
plot(nc["BIR74"])

creates output on the default device, but no object that can be 
manipulated. Using:

par(mfrow=c(2,2))
plot(nc["BIR74"])

gives exactly the same output, because sf's plot() itself takes control of 
the graphics device, so ignoring the request for multiple panels.

par(mfrow=c(1,1))
plot(nc["BIR74"])
gridGraphics::grid.echo()
library(grid)
g <- grid.grab()
grid.newpage()
gridExtra::grid.arrange(g, b, ncol=2)

gives two copies of our initial output after conversion to grid graphics.

However, it is easier to choose alternatives:

library(tmap)
tm_shape(nc) + tm_fill(c("BIR74", "BIR79"))

and probably library(mapsf) too, but it, like sf, uses base graphics; it 
respects par(mfrow=):

library(mapsf)
par(mfrow=c(1,2))
mf_map(x=nc, var=c("BIR74"), type="choro")
mf_map(x=nc, var=c("BIR79"), type="choro")

Hope this clarifies,

Roger