Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image vs ggplot: how to plot color legend?

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

like image 670
user3036416 Avatar asked Dec 05 '25 16:12

user3036416


2 Answers

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

like image 181
jbaums Avatar answered Dec 07 '25 07:12

jbaums


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.

like image 39
lukeA Avatar answered Dec 07 '25 05:12

lukeA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!