ggplot 切断州边界线

问题描述 投票:0回答:1

我正在尝试创建一张围绕亚利桑那州和索诺拉州的地图,其中包含美国和墨西哥的政治边界线。我使用

geodata
为美国和墨西哥蛀虫创建了数据框。这些似乎在低缩放下很好地绘制在我的谷歌衍生的底图上。当我限制 x 和 y 限制以放大我的焦点区域时,就会出现问题。边界线不会延伸到放大图的末尾。这几乎就像 ggplot 的边界实际上并没有延伸到底图的整个范围。知道这里发生了什么,或者我该如何解决它?另外,不幸的是,我的代码需要一个 API 密钥,因此如果您没有 API 密钥,您可能无法运行所有代码。抱歉!

library(maps)
library(ggmap)
library(ggplot2)
library(geodata)



options( geodata_default_path = "C:/PATH")

#Download USA Spatial Vector Data
USA <- geodata::gadm(country = "USA", level = 1, version = "latest")

#plot border spatial vector
plot(USA, xlim = c(-124.732453,-66.983690), ylim = c(24.445430,49.39), col = "lightyellow")

#draw a box around the plot
box()

#set coords for the extent
coords <- list(x=c(-124.732453,-66.983690), y = c(24.445430,49.39)) #extent determined by

#create the new extent
New_extent <- extent(coords)

#clip the spatial vector to the new extent
USA <- crop(USA, New_extent)

#plot the clipped spatial vector
plot(USA)

#duplicate the spatial vector
country <- USA

#turn the spatial vector into a spatial polygons dataframe
country <- as(country, "Spatial")

#convert spatial vector to dataframe
country_map <- fortify(country)

#download USA spatial vector data
Mexico <- geodata::gadm(country = "Mexico", level = 1, version = "latest")

#plot border spatial vector
plot(Mexico, xlim = c(-120, -85), ylim = c(33, 15), col = "lightyellow")

#draw a box around the plot
box()

#set coords for the extent
coords <- list(x=c(-120,-105), y = c(25,33)) #extent determined by

#create the new extent
New_extent <- extent(coords)

#clip the spatial vector to the new extent
Mexico <- crop(Mexico, New_extent)

#plot the clipped spatial vector
plot(Mexico)

#turn the spatial vector into a spatial polygons dataframe
Mexico <- as(Mexico, "Spatial")

#convert spatial vector to dataframe
Mexico_map <- fortify(Mexico)



#set API
ggmap::register_google(key = "YOURKEY")

#Create a satellite map centering over the study area
base<-get_map("Nogales, Sonora", source="google",maptype="satellite",zoom=5)
ggmap(base)

#Add political border lines for the US and Mexico
base<-ggmap(base)+
  geom_path(data=country_map,aes(x=long,y=lat,group=group),size=0.1)+
  geom_path(data=Mexico_map,aes(x=long,y=lat,group=group),size=0.1)
base

这是缩小的地图。澄清一下,我知道并非所有墨西哥的边界都已绘制。就我的目的而言,我只需要索诺拉州的州边界线。

#restrict the x and y axes to zoom in on the study area
base.zoomin<-base+
  scale_x_continuous(limits = c(-116.5, -107))+
  scale_y_continuous(limits = c(27, 38))
base.zoomin 

这是放大的地图。请注意,边界线不会延伸到地图的边缘。我有什么办法可以解决这个问题吗?我意识到这没什么大不了的,我只是想创建一张高品质的地图。谢谢!

r ggplot2 ggmap geom
1个回答
0
投票

弄清楚了,只需将

expand = c(0, 0)
添加到
scale_x_continuous()
scale_y_continuous()
函数即可。

© www.soinside.com 2019 - 2024. All rights reserved.