在 ggmap 中添加比例尺和指北针,而不使用 ggsn

问题描述 投票:0回答:1

我最近将我的R版本更新到4.3.2,它不支持ggsn包,所以我无法使用它的比例尺和指北针功能。因此,我考虑了以下简单的代码:

library("ggplot2")
library("ggmap")


cy <- c(left = 32.2, bottom = 34.5, right = 34.8, top = 35.8)
CY_map <- get_stadiamap(cy, zoom = 10, maptype = "stamen_terrain") %>% ggmap()

它创建了一个名为 CY_map 的“gg”“ggplot”对象(注意:我使用了 get_stadiamap 而不是 get_stamenmap,因为现在不支持后者。但是,重要的是存在 gg 对象)。

然后,我将 gg 对象与 ggplot 结合起来:

long  <- c(33.0,  33.5)
lat <- c(34.75, 35.0)
df <- data.frame(long, lat)

ggCY <- CY_map +       
  geom_point( data = df,    aes(x = long, y = lat), col="red", size =  3.5   )       + 
  xlab("Longitude (°E)") + ylab("Latitude (°S)" )                                               +
  theme(axis.text.x  = element_text(size = 20),axis.text.y  = element_text(size = 20) )         +
  theme(axis.title.x = element_text(size = 26),axis.title.y = element_text(size = 26) )         +
  theme(legend.title=element_text(size=15),legend.text=element_text(size=15),legend.position = c(0.93,    0.13)) +   
  scale_color_gradientn(colours = c('#5749a0', '#0f7ab0', '#00bbb1',
                                             '#bef0b0', '#fdf4af', '#f9b64b',
                                             '#ec840e', '#ca443d', '#a51a49'))

获取以下地图:

但是我找不到在不使用 ggsn 的情况下添加比例尺和指北针的方法。直到我使用 ggspatial,它允许我添加指北针:

ggCY2 <- ggCY + ggspatial::annotation_north_arrow(location = "tl", 
    pad_x = unit(0.4, "in"), pad_y = unit(0.4, "in"),
    style = ggspatial::north_arrow_nautical(fill = c("grey40", "white"),line_col = "grey20",text_family = "ArcherPro Book"))

但是,我无法添加比例尺:

ggCY3 <- ggCY2 + annotation_scale(location = "bl", width_hint = 0.5)
ggCY3

因为我收到以下错误:

Error in `annotation_scale()`:
! Problem while converting geom to grob.
ℹ Error occurred in the 6th layer.
Caused by error in `draw_panel()`:
! Don't know how to create scalebar using CoordMap/Coord/ggproto/gg

有什么建议吗?

r ggplot2 ggmap
1个回答
0
投票

annotation_scale()
需要一些上下文来找出比例尺所使用的坐标(十进制度)和长度单位之间的关系,通常期望看到
coord_sf
以及使用
 时默认获得的坐标参考系sf
对象和
geom_sf()
而不是
geom_point()
。虽然添加
coord_sf()
应该可以正常工作:

ggCY3 <- ggCY2 + 
  annotation_scale(location = "bl", width_hint = 0.5) + 
  coord_sf(crs = 4326)
#> Coordinate system already present. Adding new coordinate system, which will
#> replace the existing one.
ggCY3

© www.soinside.com 2019 - 2024. All rights reserved.