Hi I have a matrix 37x73 that represent one variable (moavg) gridded with a 10x10 deg spacing (-180< LON< 180 e -90 < LAT< 90). I am able to plot it using image
image(LON, LAT, moavg)
but I can't display the colour bar. I would like to know if there is another function to do that (maybe ggplot) that allows me also to plot the colour legend.
Many thanks
For plotting gridded spatial data, the raster
and rasterVis
packages are also useful.
Here are a couple of examples:
library(rasterVis) # this will also load the raster package
# Create a raster from a matrix of dummy data
m <- matrix(runif(36*18), ncol=36)
r <- raster(m)
# Set the extent of the object
extent(r) <- c(-180, 180, -90, 90)
# plot with raster
plot(r)
# plot with rasterVis
levelplot(r, margin=FALSE)
If your gridded data exists in a file (e.g. .asc, .tif, etc.), then you can load it by giving raster()
a file path, e.g. raster('C:/path/to/moavg.asc')
, and you shouldn't need to set the extent in that case since the file should contain this metadata.
See ?raster
and ?levelplot
for more details.
Plotting with raster
Plotting with levelplot
EDIT
To address the extension to this question found in the comments, here is one way to overlay a polygon:
library(maps)
levelplot(r, xlab='longitude', ylab='latitude', margin=FALSE,
panel = function(x, y, ...) {
panel.levelplot(x, y, ...)
mp <- map("world", plot = FALSE, fill=TRUE)
lpolygon(mp$x, mp$y)
})
With regards to this answer:
library(fields)
image.plot(lon, lat, moavg, col=heat.colors(8))
PS: Please be so kind to provide a reproducible example in your question. Here's how it works.