首页 > 解决方案 > 为什么我的 ggmap 比例尺显示在屏幕外/根本不显示?

问题描述

我正在尝试在我的地图上添加一个 20 公里的比例尺,但我尝试的每个解决方案要么在屏幕外添加比例尺(你只能看到“km”的底部),要么根本不添加它。

我最接近的是使用 scalebar(),它在屏幕外添加了一个比例尺,但不允许我将它移动到完全可见的状态。我也尝试过用 geom_line 等从头开始制作一个栏,但根本没有绘制。

这是一张可重现的地图,没有尝试制作比例尺和一小组坐标

library(ggmap)
library(ggsn)

wd <- getwd()

Latitude <- c(34.1365, 34.14435, 34.05111, 34.17605)

Longitude <- c(-117.92391, -117.85036, -118.31712, -118.31712)

graphingdata <- cbind.data.frame(Latitude,Longitude)

# compute the bounding box
bc_bbox <- make_bbox(lat = as.numeric(graphingdata$Latitude), lon = as.numeric(graphingdata$Longitude))

bc_bbox

# grab the map from google


site_map <- get_stamenmap(bc_bbox, zoom = 10, maptype = "terrain")

#create and save the map
png(file=paste0(wd,"stack-ex-graph.png"))

map <- ggmap(site_map, legend = "bottom") + 
  geom_point(data = graphingdata, aes(x = as.numeric(Longitude), 
                                      y = as.numeric(Latitude)), color = "red", size = 2) + 

    ggtitle(paste0("This is the map title"), 
          subtitle = paste0("This is the subtitle"))
print(map)
dev.off()

标签: rggplot2mappingggmap

解决方案


我最终能够使用锚参数来移动比例尺的位置。由于项目的范围,我使地图的锚点和边界变得灵活。

#Create the data frame    
Latitude <- c(34.1365, 34.14435, 34.05111, 34.17605)

    Longitude <- c(-117.92391, -117.85036, -118.31712, -118.31712)

    graphingdata <- cbind.data.frame(Latitude,Longitude)

#Set up bounding box
    height <- max(graphingdata$Latitude) - min(graphingdata$Latitude)
    width <- max(graphingdata$Longitude) - min(graphingdata$Longitude)
    sac_borders <- c(bottom  = min(graphingdata$Latitude)  - 0.1 * height, 
                     top     = max(graphingdata$Latitude)  + 0.1 * height,
                     left    = min(graphingdata$Longitude) - 0.1 * width,
                     right   = max(graphingdata$Longitude) + 0.1 * width)

 #Get the site map
 map <- get_stamenmap(sac_borders, zoom = 10, maptype = "terrain")    
 map <- ggmap(site_map, legend = "bottom")+ 
          scalebar(x.min = sac_borders[[3]]-1, x.max = sac_borders[[4]]+1,y.min = sac_borders[[1]]-1, y.max = sac_borders[[2]]+1,transform = TRUE,
                   dist = 20,dist_unit = "km",model = "WGS84",anchor = c(x=sac_borders[[3]]+0.6,y=sac_borders[[1]]+0.25), st.size = 2, border.size = 0.5)+
          geom_point(data = graphingdata, aes(x = as.numeric(Longitude), 
                                              y = as.numeric(Latitude)), color = "red", size = 2) + 
          ggtitle(paste0("This is the map title"), 
                  subtitle = paste0("This is the subtitle"))

示例输出映射。可以使用锚参数移动比例尺。缩放可以在 get_stamenmap() 中修改。 示例输出映射。


推荐阅读