Reputation: 535
I have been trying to colour the ocean in white or transparent in the code below, but have been unsuccessful so far. I have seen other posts on Stack but couldn't apply them to my example (e.g. How can I color the ocean blue in a map of the US?). I welcome suggestions. Thank you very much!
library(raster)
library(ggplot2)
library(maptools)
data("wrld_simpl")
#sample raster
r <- raster(ncol=10, nrow=20)
r[] <- 1:ncell(r)
extent(r) <- extent(c(-20, 20, -20, 20))
#plotting
var_df <- as.data.frame(rasterToPoints(r))
p <- ggplot() +
geom_polygon(data = wrld_simpl[wrld_simpl@data$UN!="10",],
aes(x = long, y = lat, group = group),
colour = "black", fill = "grey") # does the fortification automatically
p <- p + geom_raster(data = var_df, aes(x = x, y = y, fill = layer))
p <- p + coord_equal() + theme_bw() +labs(x="", y="")
p <- p + theme(legend.key=element_blank(),
axis.text.y =element_text(size=16),
axis.text.x =element_text(size=16),
legend.text =element_text(size=12),
legend.title=element_text(size=12))
p <- p + scale_fill_gradientn(colours = rev(terrain.colors(10)))
p <- p + geom_polygon(data = wrld_simpl[wrld_simpl@data$UN!="10",],
aes(x = long, y = lat, group = group),
colour = "black", fill = NA)
p
Upvotes: 1
Views: 1091
Reputation: 1233
My interpretation of your question is that you want to show the raster over the land surface but not over the ocean. To do this it is easier to mask
the raster by the land surface, I disaggregated the raster first to make the edges smoother:
#sample raster
r <- raster(ncol=10, nrow=20)
r[] <- 1:ncell(r)
extent(r) <- extent(c(-20, 20, -20, 20))
r=disaggregate(r,10)
r=mask(r,wrld_simpl)
#plotting
var_df <- as.data.frame(rasterToPoints(r))
p <- ggplot() +
geom_polygon(data = wrld_simpl[wrld_simpl@data$UN!="10",],
aes(x = long, y = lat, group = group),
colour = "black", fill = "grey") # does the fortification automatically
p <- p + geom_raster(data = var_df, aes(x = x, y = y, fill = layer))
p <- p + coord_equal() + theme_bw() +labs(x="", y="")
p <- p + theme(legend.key=element_blank(),
axis.text.y =element_text(size=16),
axis.text.x =element_text(size=16),
legend.text =element_text(size=12),
legend.title=element_text(size=12))
p <- p + scale_fill_gradientn(colours = rev(terrain.colors(10)))
p <- p + geom_polygon(data = wrld_simpl[wrld_simpl@data$UN!="10",],
aes(x = long, y = lat, group = group),
colour = "black", fill = NA)
p
Upvotes: 5