I am trying to place a world map on my current plots made by level plot. This plot was made as follows:
library(raster)
library(ncdf4)
library(maps)
library(maptools)
library(rasterVis)
library(ggplot2)
library(rgdal)
library(sp)
library(gridExtra)
MFplot4<-levelplot(MFMeaner3,margin=F, at=Fcutpoints4,cuts=11,
pretty=TRUE,par.settings=mapTheme, main="Historical five-day maximum
precipitation (mm/day) model mean")
The object "MFMeaner3" has the following attributes:
class : RasterLayer
dimensions : 64, 128, 8192 (nrow, ncol, ncell)
resolution : 2.8125, 2.789327 (x, y)
extent : -181.4062, 178.5938, -89.25846, 89.25846 (xmin, xmax, ymin,
ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names : layer
values : 0.1583802, 164.2064 (min, max)
Here was my attempt to place a world map overlay on the above plot:
world.outlines<-map("world", plot=FALSE)
world.outlines.sp<-map2SpatialLines(world.outlines,proj4string =
CRS("+proj=longlat"))
MFplot4 + layer(sp.lines(world.outlines.sp,col="black",lwd=0.5))
However, this leads to the following error:
Error: Attempted to create layer with no stat.
I also tried placing a simple world map using this:
MFplot4 + plot(wrld_simpl)
But I receive this error:
Error in UseMethod("as.layer") :
no applicable method for 'as.layer' applied to an object of class "NULL"
Why would these errors occur?
Any assistance with this would be extremely appreciated!
The issue is that, by loading ggplot2, you have masked the latticeExtra::layer()
function (attached by rasterVis) with ggplot2::layer()
. If you must load ggplot2, then you'll want to fully qualify your call to the masked function, writing latticeExtra::layer()
in place of layer()
.
Here is a reproducible example that works for me when ggplot is not loaded, but fails when it is:
library(rasterVis)
library(sp)
library(maps)
library(maptools)
## library(ggplot2) ## `levelplot() + layer()` fails when this is loaded
## Read in a RasterLayer
tmax <- getData('worldclim', var='tmax', res=10)[[6]]
## Create a SpatialLines object
countries <- map("world", plot=FALSE)
countries <- map2SpatialLines(countries, proj4string = CRS("+proj=longlat"))
## Overlay lines on levelplot
levelplot(tmax, margin=FALSE) +
layer(sp.lines(countries))