3

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

smci
  • 32,567
  • 20
  • 113
  • 146
user3036416
  • 1,205
  • 2
  • 15
  • 28

2 Answers2

4

With regards to this answer:

library(fields)
image.plot(lon, lat, moavg, col=heat.colors(8))

enter image description here

PS: Please be so kind to provide a reproducible example in your question. Here's how it works.

Community
  • 1
  • 1
lukeA
  • 53,097
  • 5
  • 97
  • 100
4

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 raster plot example

Plotting with levelplot levelplot example


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)
            })

levelplot with overlay

jbaums
  • 27,115
  • 5
  • 79
  • 119
  • Hi, that is great! How can I set the axes names and overlay a world map? I tried with map(add=T) bat it is not working.. – user3036416 Feb 10 '14 at 19:30
  • Hi, what about instead to scale the map according to the spacing of the gridded field? Thanks – user3036416 Feb 11 '14 at 11:31
  • Not quite sure what you mean. Maybe post it as a new question if you can't find a relevant answer on SO. If you're asking how to adjust the points at which the legend changes colours, then use the `at` argument to supply a vector of numbers (as described under `?lattice::levelplot`). – jbaums Feb 11 '14 at 11:56
  • Hi I posted it in http://stackoverflow.com/questions/21699809/scale-world-map-in-r – user3036416 Feb 11 '14 at 12:32