为什么我的ggmap比例尺显示在屏幕外/根本不显示?

时间:2019-08-28 20:34:34

标签: r ggplot2 mapping ggmap

我正在尝试向地图添加20公里的比例尺,但是我尝试过的每个解决方案要么在屏幕上添加比例尺(您只能看到“千米”的底部),要么不将其添加到全部。

我最接近的是使用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()

1 个答案:

答案 0 :(得分:0)

我最终可以使用anchor参数移动比例尺的位置。由于项目的范围,我使地图的锚定和定界变得灵活。

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

示例输出图。比例尺可以与anchor参数一起移动。可以在get_stamenmap()中修改缩放。 Example output map.