在下面的代码中,我一直试图将海洋着色为白色或透明,但到目前为止仍未成功。我在Stack上看到过其他帖子,但无法将其应用于我的示例(例如How can I color the ocean blue in a map of the US?)。我欢迎提出建议。非常感谢你!
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
答案 0 :(得分:4)
我对您的问题的解释是,您希望将栅格显示在陆地表面而不是海洋上。为此,更容易通过陆地表面mask
栅格,我首先对栅格进行了分解以使边缘更平滑:
#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