ggplot2:使用多个元素创建的地图未保存在图像中

ggplot2: Map create with several elements is not saved in the image

我想用我的目标坐标在 ggplot2 中创建一个地图,例如指北针和比例尺,但是尽管 ggsave() 函数保存了最后一个图,但它没有不适用于 mymap.png 图片。 在我的例子中:

#Packages
library(ggplot2)
library(ggsn)

# Get data set - x any are the points
all.stands.predict<-read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/prediction__bug_2021-03-18.csv")
all.stands.predict<-all.stands.predict[all.stands.predict[,3]=="VILA PALMA",] # Area selection

#Create a map
gg <- ggplot() +
  geom_point(data=all.stands.predict, 
  aes(x=x, y=y), color="red") +
  xlab("Latitude") + ylab("Longitude") +
  theme_bw() 

#Add a scale bar.
gg <- gg + scalebar(location="bottomright",y.min=max(all.stands.predict$y)-0.001, y.max=max(all.stands.predict$y), 
             x.min=max(all.stands.predict$x)-0.001, x.max=max(all.stands.predict$y), model='WGS84',
             transform=TRUE)
#

#Add a north arrow
north2(gg, 0.85, 0.85, symbol = 10)

#Save image in png
ggsave("mymap.png", dpi=300, width = 20, height = 20)   
#

当我检查我创建的“mymap.png”图像时,只显示了指北针,看起来像这样:

请问,保存所有地图元素有什么想法吗?

提前致谢!

ggspatial 包可能有更好的解决方案:

#Packages
library(ggplot2)
library(ggspatial)
library(sf)

# Get data set - x any are the points
all.stands.predict<-read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/prediction__bug_2021-03-18.csv")
all.stands.predict<-all.stands.predict[all.stands.predict[,3]=="VILA PALMA",] # Area selection

#Create a map
(sites <- st_as_sf(all.stands.predict, coords = c("x", "y"), 
                   crs = 4326, agr = "constant"))
gg <- ggplot() +
  geom_sf(data=sites, color="red") +
  annotation_north_arrow(location = "bl", which_north = "true", 
                         pad_x = unit(0.3, "in"), pad_y = unit(0.5, "in"),
                         style = north_arrow_fancy_orienteering) + #Add a north arrow
  annotation_scale(location = "bl", width_hint = 0.55) + #Add a scale bar
  xlab("Latitude") + ylab("Longitude") +
  theme_bw() 
plot(gg)
ggsave("mymap.png", dpi=300, width = 20, height = 20)