将比例尺添加到使用coord_sf缩放的ggplot地图?

将比例尺添加到使用coord_sf缩放的ggplot地图?,r,ggplot2,sf,R,Ggplot2,Sf,我使用sf软件包和ggplot2制作了一张地图: library(ggplot2) library(sf) library(rnaturalearth) state_prov <- rnaturalearth::ne_states(c("united states of america", "canada"), returnclass="sf") x <- ggplot(data=state_prov) + geom_sf

我使用sf软件包和ggplot2制作了一张地图:

library(ggplot2)
library(sf)
library(rnaturalearth)
state_prov <- rnaturalearth::ne_states(c("united states of america", "canada"), returnclass="sf")
x <- ggplot(data=state_prov) + 
geom_sf()+
coord_sf(xlim=c(-170, -95), ylim=c(40, 75)) 
print(x)
库(ggplot2)
图书馆(sf)
图书馆(rnaturalearth)

如您所述,如果您注释掉代码的
coord\u sf
部分,则会显示比例尺。我的猜测是
ggsn::scalebar
必须从整个
state\u prov
数据集中获取其
topleft
位置,当您使用
coord\u sf
进行缩放时,缩放栏将被裁剪

编辑:将比例尺放置在具有此比例尺的lat/long投影的地图上时,请注意极端失真:

这里有几个选项可以让比例尺显示出来

选项1

使用
ggspatial::annotation_scale
代替
ggsn
,后者似乎可以识别
coord_sf
中定义的缩放

ggplot(data=state_prov) + 
  geom_sf()+
  coord_sf(xlim=c(-170, -95), ylim=c(40, 75)) +
  ggspatial::annotation_scale(location = 'tl')

选项2

使用原始代码,但在打印前裁剪
状态
,以便
比例尺
可以找到正确的
左上方

state_prov_crop <- st_crop(state_prov, xmin=-170, xmax = -95, ymin = 40, ymax = 75)

ggplot(data=state_prov_crop) + 
  geom_sf()+
  #coord_sf(xlim=c(-170, -95), ylim=c(40, 75)) +
  ggsn::scalebar(state_prov_crop, location="topleft", dist = 50, dist_unit = "km", 
                 transform=TRUE, model="WGS84", height=0.1)

state\u prov\u作物谢谢!选项1对我来说非常有效。别担心,我会在某个时刻改变投影,以避免失真问题。
state_prov_crop <- st_crop(state_prov, xmin=-170, xmax = -95, ymin = 40, ymax = 75)

ggplot(data=state_prov_crop) + 
  geom_sf()+
  #coord_sf(xlim=c(-170, -95), ylim=c(40, 75)) +
  ggsn::scalebar(state_prov_crop, location="topleft", dist = 50, dist_unit = "km", 
                 transform=TRUE, model="WGS84", height=0.1)