添加距离比例尺

时间:2018-11-02 20:45:21

标签: r ggplot2

我想在图形中添加一个比例尺,并且尝试按照其他人的建议使用ggsn包,但收效甚微(我无法获得正确的比例尺和位置的比例尺)

感谢您的帮助。

代码:

base1 = get_map(location=c(-75,44.5,-72,47), maptype = "toner-background")
map2 = ggmap(base1)
sites <- read.table("sites.txt", header = T)

map2 + geom_point(data=sites, aes(x=long, y=lat), color="blue", cex=2) +
  scale_fill_manual( name=NULL) +
  scale_shape_manual(name=NULL) + 
  labs(x="Longitude", y="Latitude", title="Collection sites", cex.lab =2) + 
  theme_bw() + theme(legend.position="bottom", axis.text = element_text(size = rel(1.33)), axis.title=element_text(size=15,face="bold"), legend.key = element_rect(colour = "blue"), axis.text.x = element_text(angle=45, vjust=0.5)) +
  scalebar(data = NULL,dist = 40,location = "topleft", dd2km = TRUE, model = 'WGS84',
           x.min = -72, x.max = -75, y.min = 44.5, y.max = 47, height = 0.90)

#REQUIRED PACKAGES
install.packages("ggplot2")
install.packages("ggmap")
install.packages("maps")
install.packages("mapproj")
install.packages("mapdata")
install.packages("rgeos")
install.packages("maptools")
install.packages("sp")
install.packages("raster")
install.packages("rgdal")
install.packages("dismo")
install.packages('ggsn')

require(ggplot2)
require(ggmap)
require(maps)
require(mapproj)
require(mapdata)
require(rgeos)
require(maptools)
require(sp)
require(raster)
require(rgdal)
require(dismo)
require(ggsn)

enter image description here

1 个答案:

答案 0 :(得分:2)

您不小心设置了x.min = -72,并且x.max = -75必须相反,因为-75 < -72。经过一些调整后,我能够以这种方式绘制它:

# library(ggmap)
#
# base1 = get_map(location = c(-75, 44.5, -72, 47), maptype = "toner-background")
# map2 = ggmap(base1)
#
# set.seed(53125597)
#
# sites <- data.frame(lon = sample(seq(-75, -72, .1), 6), 
#                     lat = sample(seq(44.5, 47, .1),  6)
#                     )
#

limts <- c(xmin =  .2 + min(map2$data$lon),
           xmax = -.2 + max(map2$data$lon),
           ymin =  .1 + min(map2$data$lat),
           ymax = -.1 + max(map2$data$lat)
           )
map2 + 
  geom_point(data = sites, aes(x = lon, y = lat), color = "blue") +
  labs(title = "Collection sites", x = "Longitude", y = "Latitude") + 
  ggsn::scalebar(dist = 40, dd2km = TRUE, model = 'WGS84',
                 x.min = limts[1], x.max = limts[2],  
                 y.min = limts[3], y.max = limts[4], 
                 location = "topleft", st.size = rel(2.5)
                 ) + 
  theme_bw() + 
  theme(
    axis.text  = element_text(size = rel(1.33)),
    axis.title = element_text(size = 15, face = "bold"),
    axis.text.x = element_text(angle = 45, vjust = 0.5)
    )

map