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

RStudio中为地图添加比例尺与坐标失败的问题求助

问题:ggplot地图无法显示比例尺和坐标的解决方法

我尝试用以下RStudio代码为地图添加比例尺和坐标:

library(dplyr)
library(readr)
library(ggplot2)
library(leaflet)
library(ggspatial)

ged <- read_csv("GEDEvent_v23_0_11.csv")

ged_confl <- ged |> 
filter(country == "DR Congo (Zaire)")
pal_num <- colorNumeric(palette = "inferno", 
domain = ged_confl$best, 
reverse = TRUE)

ged_confl |> 
leaflet() |> 
addProviderTiles(providers$CartoDB.Voyager) |> 
addCircleMarkers(lng = ~longitude, 
lat = ~latitude,
popup = ~best,                   
color = ~pal_num(best),
label = ~best) |> 
addLegend(pal = pal_num, 
values = c(min(ged_confl$best):max(ged_confl$best)), 
position = "bottomright", 
title = "Nº de bajas estimadas", 
opacity = 0.8) 

ggplot(data=ged, aes(x=longitude, y=latitude)) +
geom_sf() + 
annotation_scale() + 
coord_sf() 

但最终生成的地图并未显示比例尺和坐标:

当前生成的地图
ged数据集内容

请问在ggplot中是否应该使用latitude和longitude字段来实现?


解答

你的ggplot代码存在两个核心问题,导致比例尺和坐标未显示:

  • geom_sf()使用错误:geom_sf()专门用于绘制sf类型的空间矢量数据,但你的ged只是普通经纬度表格,未转换成sf对象,直接调用geom_sf()不会生成任何图形,自然无法触发比例尺和坐标的渲染。
  • 经纬度字段的用法不符合ggplot空间绘图逻辑:普通经纬度数据不能直接配合geom_sf()使用,需转换数据类型或更换图层函数。

修正方案一:用普通点图层快速实现

直接替换geom_sf()为geom_point(),并明确指定坐标系:

ggplot(data=ged_confl, aes(x=longitude, y=latitude)) +
  geom_point(color = ~pal_num(best)) +  # 用geom_point绘制经纬度点
  annotation_scale(location = "bl") +   # 指定比例尺位置为左下角
  coord_sf(crs = 4326) +               # 指定WGS84坐标系,匹配经纬度格式
  labs(x = "经度", y = "纬度")

修正方案二:转换为sf对象(规范空间数据处理)

推荐将普通经纬度数据转换成sf对象,这样能更好兼容ggspatial的空间标注功能:

library(sf)

# 将经纬度列转换为sf空间对象,指定坐标系为WGS84(EPSG:4326)
ged_sf <- st_as_sf(ged_confl, coords = c("longitude", "latitude"), crs = 4326)

ggplot(ged_sf) +
  geom_sf(color = ~pal_num(best)) +  # 此时可正常使用geom_sf绘制
  annotation_scale(location = "bl") +
  coord_sf() +  # sf对象自带坐标系信息,可省略crs参数
  labs(x = "经度", y = "纬度")

额外补充

  • 你之前的leaflet代码是正常工作的,若要给leaflet地图加比例尺,需添加addScaleBar():
|> addScaleBar(position = "bottomleft")
  • annotation_scale()依赖明确的投影坐标系(crs),所以coord_sf()中指定crs是关键,否则比例尺无法正确计算显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:51:01