如何使用ggplot 2将底图添加到spatraster图中?

pnwntuvh  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(152)

我想使用ggplot2和terra包将此底图添加到栅格中,但我被卡住了。您能帮我解决这个问题吗?

library(basemaps)
library(terra)
Library(rasterVis)

set_defaults(Yiel_total , map_service = "esri" , map_type = "world_hillshade")
x <- basemap_magic(Yiel_total , map_service = "esri" , map_type = "world_hillshade")
#Yiel_total was used for the extent

SpatRaster Data表示总收益
ggplot代码:

Yield <-rast("Yield_total")
Yield_Tot_6 <- gplot(Yield ) + geom_tile(aes(fill = value)) + ggtitle("")+
  theme(panel.spacing.x=unit(0,"lines"), axis.title.x = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(),
        axis.title.y = element_blank(),plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),strip.background = element_blank(),
        strip.text = element_text(size = 14, color = "black", face = "bold"),legend.text = element_text(size = 14, face = "bold"),
        legend.title = element_text(hjust = 0.1, size = 16, face = "bold"), panel.background = element_blank()) +
  guides(fill = guide_colourbar(title = "Relative yield",title.hjust = 0.5, barheight = 15, barwidth = 2))+ 
  #basemap_magic(Yield_0.5_6, map_service = "esri" , map_type = "world_hillshade")+
  
  facet_wrap(~ variable, ncol = 3 ) +
  scale_fill_gradient(limits = c(0.01,0.88),low = 'red', high = 'dark green', na.value = "grey93", breaks = c(0.02,0.20, 0.40, 0.60,0.75, 0.87))

Yield_Tot_6

6mw9ycah

6mw9ycah1#

您可以使用tidyterra轻松处理ggplot2和SpatRasters。我修改了对basemap_raster的调用,并将其转换为SpatRaster:

library(basemaps)
library(terra)

Yiel_total <- rast("Yiel_total.tif")

set_defaults(Yiel_total, map_service = "esri", map_type = "world_hillshade")
x <- basemap_raster(Yiel_total, map_service = "esri", map_type = "world_hillshade")
x_terr <- rast(x)

library(ggplot2)
library(tidyterra)

ggplot() +
  geom_spatraster_rgb(data = x_terr) +
  geom_spatraster(data = Yiel_total) +
  # Faceting with tidyterra
  facet_wrap(~lyr, ncol = 3) +
  scale_fill_gradient(
    limits = c(0.01, 0.88), low = "red", high = "dark green",
    na.value = NA, breaks = c(0.02, 0.20, 0.40, 0.60, 0.75, 0.87)
  ) +
  ggtitle("") +
  theme(
    panel.spacing.x = unit(0, "lines"), axis.title.x = element_blank(),
    axis.text = element_blank(), axis.ticks = element_blank(),
    axis.title.y = element_blank(), plot.title = element_text(
      hjust = 0.5,
      size = 18, face = "bold"
    ), strip.background = element_blank(),
    strip.text = element_text(size = 14, color = "black", face = "bold"),
    legend.text = element_text(size = 14, face = "bold"),
    legend.title = element_text(hjust = 0.1, size = 16, face = "bold"), 
    panel.background = element_blank()
  ) +
  guides(fill = guide_colourbar(
    title = "Relative yield", title.hjust = 0.5,
    barheight = 15, barwidth = 2
  ))

相关问题