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

使用ggplot2和sf绘制地图时,如何添加右侧及顶部刻度与刻度标签?

解决ggplot2+sf地图四边显示刻度与标签的问题

你遇到的问题是因为使用coord_sf()时,ggplot会启用空间专用坐标轴,常规的scale_x_continuous()/scale_y_continuous()设置无法覆盖空间轴的行为。要让地图四边都显示刻度和标签,需要通过主题(theme)参数直接控制顶部和右侧的轴元素:

修改后的完整代码

library("ggplot2")
library("sf")
library("rnaturalearth")

us <- ne_countries(scale = "medium", returnclass = "sf")

bb <- st_sfc(
  st_polygon(list(cbind(
    c(-119, -74, -74, -119, -119), 
    c(22, 22, 51, 51, 22) 
  ))), crs = "WGS84") %>%
  st_transform(crs = st_crs("ESRI:102003"))

ggplot() +
  geom_sf(data = us, fill = NA, color = "black", alpha = .9) +
  coord_sf(
    xlim = c(st_bbox(bb)["xmin"], st_bbox(bb)["xmax"]),
    ylim = c(st_bbox(bb)["ymin"], st_bbox(bb)["ymax"]),
    crs = st_crs("ESRI:102003"),
    expand = FALSE
  ) +
  xlab(NULL) + ylab(NULL) +
  theme_bw() +
  theme(
    # 启用顶部x轴的刻度和标签
    axis.text.x.top = element_text(color = "black", vjust = 0.5),
    axis.ticks.x.top = element_line(color = "black"),
    # 启用右侧y轴的刻度和标签
    axis.text.y.right = element_text(color = "black", hjust = 0),
    axis.ticks.y.right = element_line(color = "black")
  )

关键说明

  • axis.text.x.top/axis.ticks.x.top:控制顶部x轴的标签文本和刻度线样式,设置为element_text()/element_line()即可启用(默认是element_blank())
  • axis.text.y.right/axis.ticks.y.right:同理控制右侧y轴的元素
  • 可以根据需求调整angle(文本角度)、hjust/vjust(对齐方式)等参数优化显示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:26:08