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

如何使用sf与ggplot2在地图中设置精确的坐标轴刻度?

sf + ggplot2 地图X轴刻度调整方案

需求

  • 指定精确的4个X轴刻度
  • 首尾刻度标签紧贴绘图边框,无间隙

原测试代码

library(ggplot2)
library(sf)
#> Linking to GEOS 3.11.1, GDAL 3.6.2, PROJ 9.1.1; sf_use_s2() is TRUE
library(patchwork)

poly <- rnaturalearth::ne_countries(
  country = c("Canada", "Belgium"),
  scale = "medium",
  returnclass = "sf"
)

make_plot <- function(poly) {
  bbox <- st_bbox(poly)

  xmin <- bbox[1]
  xmax <- bbox[3]

  xbreaks <- pretty(seq(xmin, xmax, length.out = 4), n = 4)

  ggplot() +
    geom_sf(data = poly) +
    scale_x_continuous(breaks = xbreaks) +
    coord_sf(xlim = c(xmin, xmax), expand = FALSE)
}

p1 <- make_plot(poly[poly$name_en == "Canada", ])
p2 <- make_plot(poly[poly$name_en == "Belgium", ])

p1 + p2

问题分析

原代码依赖pretty()生成刻度,该函数会优先输出“规整”的数值,无法保证精确生成4个刻度;同时若首尾刻度未完全对齐地图边界,会导致标签与边框出现间隙。

修改后的代码

library(ggplot2)
library(sf)
library(patchwork)

poly <- rnaturalearth::ne_countries(
  country = c("Canada", "Belgium"),
  scale = "medium",
  returnclass = "sf"
)

make_plot <- function(poly) {
  bbox <- st_bbox(poly)
  xmin <- bbox[1]
  xmax <- bbox[3]
  
  # 生成精确4个等间距刻度,首尾完全对齐地图边界
  xbreaks <- seq(xmin, xmax, length.out = 4)

  ggplot() +
    geom_sf(data = poly) +
    scale_x_continuous(breaks = xbreaks, labels = ~round(.x, 2)) + # 按需调整小数位数
    coord_sf(xlim = c(xmin, xmax), expand = FALSE)
}

p1 <- make_plot(poly[poly$name_en == "Canada", ])
p2 <- make_plot(poly[poly$name_en == "Belgium", ])

p1 + p2

关键调整说明

  1. 精确刻度生成:用seq(xmin, xmax, length.out = 4)直接生成4个等间距刻度,确保数量精准,且首尾刻度完全匹配地图左右边界。
  2. 紧贴边框:coord_sf(expand = FALSE)取消绘图区域与边框的默认间隙,配合首尾刻度对齐边界,实现标签紧贴边框的效果。
  3. 标签优化:通过labels = ~round(.x, 2)简化刻度标签的小数位数,可根据地图坐标精度自行调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:05:30