【发布时间】:2021-11-09 18:24:56
【问题描述】:
我有一堆栅格,我想找到它的平均值。我已经做了。现在,我想在我得到的光栅图像的平均值上添加多边形。然后,我想通过使用 ggplot2 代码保存并使其丰富多彩。但我不明白如何以及在 ggplot2 中添加多边形的位置。
fs <- list.files(path="directory.tiff", pattern =
"tif$", full.names = TRUE)
s<- raster::stack(fs)
pg <- readOGR("parks.shp")
se1 <- calc(s, fun = mean)
plot(se1)
plot(pg, add= T )
他们给了我这张附在下面的图片,公园覆盖在栅格的平均值上。到现在都还好。
但是当我使用 ggplot 来改变它的配色方案时。他们给了我想要的图案,但问题是公园多边形没有覆盖在最终图片上(在我得到的代码之后附在下面)。所以谁能告诉我我需要在哪里更改 ggplot 中的代码才能在图片 2 上获得 park shp 覆盖。
conti_col_pal <- pnw_palette("Bay",10,type="continuous")
binary.cols <- c("1" = conti_col_pal[10], "0" = "white")
cv.df <- as.data.frame(rasterToPoints(se1))
##above I give the comand of se1 when I add pg here instead it give me error.
p_cv <- ggplot() +
coord_fixed() +
geom_raster(data = xy_FONDO, aes(lon, lat, fill = r)) +
scale_fill_gradient(low = "gray56", high = "gray56", na.value = NA, guide = FALSE) +
new_scale("fill") +
geom_raster(data = cv.df, aes(x, y, fill = layer))+
scale_fill_gradientn(colours = conti_col_pal,
breaks = seq(-1, 7, 2), limits = c(0, 10))+
annotate(geom = "text", x = lonmin+2, y = latmax-2, vjust = 1, hjust = 0,
label = "",
color = "black", angle = 0, size=4)+
scale_x_continuous(limits = c(lonmin, lonmax), expand = c(0, 0)) +
scale_y_continuous(limits = c(latmin, latmax), expand = c(0, 0))+
theme_bw(base_family="")+
theme(
plot.margin = margin(0, 0, 0, 0, "cm"),
#panel.background = element_rect(fill = col_pal_binary[1], colour = col_pal_binary[1], size
= 0.5, linetype = "solid"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks.x=element_blank(),
axis.ticks.y=element_blank(),
legend.background = element_rect(fill=NA, size=0.3, linetype="solid", color=NA),
legend.position = c(0.8, 0.35),
legend.title= element_blank(),
legend.text = element_text(colour = "black", size = 12, angle = 0),
legend.direction = "vertical", ##vertical; horizontal
legend.title.align=0.5)+
guides(fill = guide_colorbar(## label.position = "bottom",
## title.position = "left",
label.vjust=0,
# draw border around the legend
frame.colour = "black",
barwidth = 1.5,
barheight = 8))
tiff(filename = "bay.tiff", res = 600,
width = 4080, height = 3200, compression = "lzw")
grid.arrange(p_cv,
ncol = 1)
dev.off()
【问题讨论】:
-
如果没有实际的数据集,很难完全回答,但看起来您的绘图代码中只有两个几何图形(均为
geom_raster)。如果您想绘制多边形,您可能需要使用geom_polygon并使用group=美学定义多边形外壳的绘制位置。这里的顺序很重要,因为 ggplot 将按照它们在代码中出现的顺序绘制图层。因此,geom_polygon()应该出现在geom_raster调用之后,以便将它们绘制在它们之上。