rggplot2ggmap

Add scalebar and north arrow in a ggmap without using ggsn


I have recently updated my R version to 4.3.2, which does not support ggsn package, so I cannot use its functions for scalebar and north arrow. Consequently, I have considered the following simple code:

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()

which creates a "gg" "ggplot" object called CY_map (note: I have used get_stadiamap instead of get_stamenmap since the latter is not supported now. However, the important thing is that a gg object is present).

Then, I combined the gg object with 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'))

to get the following map:

enter image description here

But I could not find a way to add scalebar and northarrow without using ggsn. Until I used ggspatial, which allowed me to add the north arrow:

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"))

enter image description here

Yet, I cannot add scalebar:

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

Since I get the following error:

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

Any suggestions?


Solution

  • annotation_scale() needs some context to figure out the relation between used coordinates (decimal degrees) and length units for a scale bar, it generally expects to see coord_sf with a coordinate reference system which you'd get by default when using sf objects and geom_sf() instead of geom_point(). Though adding coord_sf() should work just fine:

    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