r - 如何在 ggplot2 中添加多边形和栅格?ggplot 后的最终绘图中缺少多边形
问题描述
我有一堆光栅,并假设找到它的平均值。我已经做了。现在,我想在我得到的光栅图像的平均值上添加多边形。然后,我想通过使用 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()
解决方案
在定义栅格“df”后,对 pg 执行相同操作,但使用函数 fortify 执行操作,类似地在“geom_raster”执行“geom_polygon”后将多边形引入 ggplot。
推荐阅读
- javascript - 覆盖 Chrome 扩展的 XMLHttpRequest 原型
- javascript - 剃须刀上的jquery选择器不会触发事件
- mysql - 有没有另一种方法来看待这样的“AND”类型的问题?
- javascript - setState 将对象添加到基于文本字段的数组的问题
- css - 为什么我的@media 中 div 的高度不会改变?
- xslt - 用于 c xsl-fo 的 Xslt 语法高亮显示
- dask - Dask Dataframe 大于延迟数字
- javascript - Webpack 无效的配置对象
- node.js - npm 脚本删除目录中的所有文件,除了具有某些扩展名的文件(mac os)
- git - 创建一个没有旧提交的分支