You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ggplot+sf的含地球与外太空投影图中,能否将外太空涂黑?

解决方案

当然可以实现这个效果,核心思路是先在绘图最底层添加黑色背景模拟外太空,再在上方绘制地球(海洋+陆地)部分。修改后的代码如下:

library(ggplot2)
library(sf)
library(grid) # 用于rectGrob,若已加载可省略

# 导入数据
df <- read_sf("https://raw.githubusercontent.com/rfortherestofus/book/refs/heads/main/data/states.geojson")

# 生成带黑色外太空的地图
ggplot() +
  # 添加覆盖整个绘图区域的黑色矩形(外太空背景)
  annotation_custom(
    grob = rectGrob(fill = "black", colour = NA),
    xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf
  ) +
  # 绘制美国州界
  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"), # 海洋颜色
    plot.background = element_rect(fill = "black", colour = NA) # 确保绘图边缘为黑色
  )

关键修改说明:

  • annotation_custom添加的黑色矩形会作为最底层背景,覆盖所有超出地球投影范围的区域(即外太空部分)。
  • plot.background设置为黑色,避免绘图区域的边缘出现非黑色的空隙。
  • 保留原有的panel.background浅蓝色作为海洋,灰色填充的陆地与黑色背景形成强烈对比,更易区分。

内容的提问来源于stack exchange,提问作者Grasshopper_NZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 14:03:12