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

如何在ggplot2中加载无城市标签的浅灰色底图?

在ggplot2中加载无标签的浅灰色底图

你可以通过以下几种方式实现无标签的浅灰色底图需求,替代leaflet中CartoDB.PositronNoLabels的效果:

方法一:直接指定CartoDB无标签瓦片URL(推荐)

ggspatial的annotation_map_tile支持直接传入瓦片服务的URL,无需依赖rosm内置的类型。CartoDB无标签浅灰瓦片的URL模板可直接替换原代码中的type参数:

library(ggplot2)
library(ggspatial)
library(sf)

# 定义纽约 bounding box(WGS84)
nyc_bbox <- st_bbox(c(xmin = -74.25, ymin = 40.45, 
                      xmax = -73.70, ymax = 40.91), 
                    crs = st_crs(4326))

ggplot() +
  # 使用CartoDB无标签浅灰瓦片URL
  annotation_map_tile(
    url = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png",
    zoom = 10
  ) +
  coord_sf(
    xlim = c(nyc_bbox[1], nyc_bbox[3]), 
    ylim = c(nyc_bbox[2], nyc_bbox[4]),
    crs = st_crs(4326)
  ) +
  theme_void()

方法二:自定义纯灰色背景画布

如果不需要真实地图的道路等元素,仅需浅灰色画布,可直接用geom_rect创建填充背景,无需加载瓦片:

library(ggplot2)
library(sf)

nyc_bbox <- st_bbox(c(xmin = -74.25, ymin = 40.45, 
                      xmax = -73.70, ymax = 40.91), 
                    crs = st_crs(4326))

ggplot() +
  # 浅灰色背景(可调整fill参数的颜色值)
  geom_rect(aes(xmin = nyc_bbox[1], xmax = nyc_bbox[3], 
                ymin = nyc_bbox[2], ymax = nyc_bbox[4]),
            fill = "#f0f0f0", color = NA) +
  coord_sf(
    xlim = c(nyc_bbox[1], nyc_bbox[3]), 
    ylim = c(nyc_bbox[2], nyc_bbox[4]),
    crs = st_crs(4326)
  ) +
  theme_void()

方法三:从leaflet导出静态图后导入ggplot

若你已有leaflet的可行代码,可通过webshot2将leaflet地图导出为图片,再在ggplot中作为背景导入:

library(leaflet)
library(ggplot2)
library(webshot2)
library(png)

# 导出leaflet地图为png
nyc_bbox <- list(
  lng1 = -74.25, lat1 = 40.45,
  lng2 = -73.70, lat2 = 40.91
)

map <- leaflet() %>%
  addProviderTiles(provider = providers$CartoDB.PositronNoLabels) %>%
  fitBounds(lng1 = nyc_bbox$lng1, lat1 = nyc_bbox$lat1,
            lng2 = nyc_bbox$lng2, lat2 = nyc_bbox$lat2)

# 导出图片
saveWidget(map, "nyc_base_map.html")
webshot("nyc_base_map.html", "nyc_base_map.png", vwidth = 800, vheight = 800)

# 在ggplot中导入图片
img <- readPNG("nyc_base_map.png")
ggplot() +
  annotation_raster(img, xmin = -74.25, xmax = -73.70, ymin = 40.45, ymax = 40.91) +
  coord_sf(crs = st_crs(4326)) +
  theme_void()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:52:34