r - 为什么我的 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()
解决方案
我最终能够使用锚参数来移动比例尺的位置。由于项目的范围,我使地图的锚点和边界变得灵活。
#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"))
推荐阅读
- java - 在java中使用反射时出现未处理的异常
- c++ - 在 CMake 中包含“私有”标头的错误
- javascript - 如何在 React Redux 中保持状态变化
- forward-declaration - 朋友声明调用“C++ 需要所有声明的类型说明符”
- python - Python 每个单元格写一个字符
- python - 遍历列表,如果列表中的任何索引值的长度 < 3。然后附加到 new_list。忽略在其他任何地方重复这些元素的索引
- c# - 在 EF Core 2.2 中使用/查询具有相同模型的多个数据库的最佳方式
- python - 检查数据框中 2 列之间的 2 个条件
- firebase - Firebase - 使用电子邮件链接登录返回错误 400
- html - Req.session 变量始终为 false