SHOW:
|
|
- or go back to the newest paste.
1 | ggproj <- function(r, lat, lon, tolerance=0.001, plot.borders=TRUE, border.color='black') { | |
2 | #r, lat, lon must be rasterLayers | |
3 | #Adapted from | |
4 | #http://stackoverflow.com/questions/43612903/how-to-properly-plot-projected-gridded-data-in-ggplot2 | |
5 | if (!compareRaster(r, lat, lon)) {stop('Inputs should have the same size and projection')} | |
6 | require(ggplot2) #needs ggplot >= 2.2.1.9000 | |
7 | require(sf) | |
8 | require(sp) | |
9 | crs <- projection(r) | |
10 | ||
11 | coords = data.frame(lat = values(lat), lon = values(lon)) | |
12 | spPoints <- SpatialPointsDataFrame(coords, | |
13 | data = data.frame(data = values(r)), | |
14 | proj4string = CRS("+init=epsg:4326")) | |
15 | orig_grid = spTransform(spPoints, crs) | |
16 | polys = as(SpatialPixelsDataFrame(orig_grid, orig_grid@data, tolerance = tolerance),"SpatialPolygonsDataFrame") | |
17 | polys_sf = as(polys, "sf") | |
18 | - | points_sf = as(orig_grid, "sf") |
18 | + | |
19 | gg <- ggplot(polys_sf) + | |
20 | geom_sf(aes(fill = data), color = "transparent") + | |
21 | theme_bw() + | |
22 | theme(panel.ontop=TRUE, panel.background=element_blank()) + | |
23 | scale_x_continuous(expand = c(0, 0)) + | |
24 | scale_y_continuous(expand = c(0, 0)) | |
25 | ||
26 | if (plot.borders) { | |
27 | require(maps) | |
28 | borders <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE)) | |
29 | gg <- gg + | |
30 | geom_sf(data = borders, fill = "transparent", color = border.color) + | |
31 | coord_sf(crs = st_crs(crs), | |
32 | xlim = st_bbox(polys_sf)[c(1,3)], | |
33 | ylim = st_bbox(polys_sf)[c(2,4)] | |
34 | ) | |
35 | } | |
36 | return(gg) | |
37 | } |