当投影视图在具有 sf 数据的 ggplot 中同时包含地球和外太空时,是否可以将外太空着色为黑色?

问题描述 投票:0回答:1

我正在制作几张美国地图,由于投影,其中一些地图同时包含地球和外太空,如下所示:

enter image description here

它是由以下代码生成的:

library(ggplot2)
library(sf)


# Import Data:
df <- read_sf("https://raw.githubusercontent.com/rfortherestofus/book/refs/heads/main/data/states.geojson")

# Create the map:
ggplot() +
  geom_sf(data = df, fill = "grey90") +
  
  coord_sf(crs = "+proj=ortho +lat_0=22.0 +lon_0=-162.5") +
  
  theme_minimal() +
  
  theme(
    panel.background = element_rect(fill = "lightblue")   # <- Set the colour for ocean
  )

我只是想知道是否有可能将外层空间(突出显示)涂成黑色以反映现实,并使地球(以及美国)在地图上更容易区分?

enter image description here

r ggplot2
1个回答
0
投票

一种选择是创建一个新的 sf 对象,它是一个覆盖整个星球的网格。您需要将其转换为您选择的投影并清除非法面板。此后,您可以简单地将其绘制为普通

sf
对象:

library(ggplot2)
library(sf)

seas <- st_polygon(list(cbind(c(seq(-180, 180, len = 100),
                                rep(0, 100),
                                seq(180, -180, len = 100),
                                rep(-180, len = 100)), 
                              c(rep(-90, 100),
                                seq(-90, 90, len = 100),
                                rep(90, 100),
                                seq(90, -90, len = 100))))) |>
  st_sfc(crs = "WGS84") |>
  st_sf() |>
  st_make_grid(n = c(200, 200)) |>
  st_transform(crs = "+proj=ortho +lat_0=22.0 +lon_0=-162.5")

val_st <- st_is_valid(seas)
seas <- seas[!is.na(val_st) & val_st]

ggplot() +
  geom_sf(data = seas, fill = "lightblue", col = "lightblue") +
  geom_sf(data = df, fill = "grey90") +
  coord_sf(crs = "+proj=ortho +lat_0=22.0 +lon_0=-162.5") +
  theme_minimal() +
  theme(panel.background = element_rect(fill = "black"),
        panel.grid = element_blank())

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.