r-如何将经度和纬度设置为地图的ggplot的轴



代码有问题,但我不知道是什么。我试图在显示巴塞罗那地区的地图上绘制地理加权回归的系数。我可以让R来绘制点或地图,但我无法覆盖它们。可能是什么问题?

系数图

ggplot(logairbnb, aes(x=x,y=y))+
geom_point(aes(colour=logairbnb$coefdist_center))+
scale_colour_gradientn(colours = terrain.colors(10), 
guide_legend(title="Coefs"))

巴塞罗那地图

ggplot(neighbourhood_fortified, aes(long,lat,colour = 
factor(id))) +
geom_polygon(fill = "white", colours = 
terrain.colors(10))+coord_equal()

当我试图覆盖图形时,轴发生了一些奇怪的事情

gwr.point1<-ggplot(logairbnb, aes(x=x,y=y))+
geom_point(aes(colour=logairbnb$coefdist_center))+
scale_colour_gradientn(colours = terrain.colors(10), guide_legend(title="Coefs"))
gwr.point1+
geom_polygon(data=neighbourhood_fortified,aes(long,lat,group=id),colour="grey")

好的,所以我发现这是有效的。

neighbourhood <- readOGR("BCN_UNITATS_ADM")
g<-as.data.frame(logairbnb$coefdist_center)
g<-cbind(logairbnb$y,g)
g<-cbind(logairbnb$x,g)
colnames(g)[1] <- "long"
colnames(g)[2] <- "lat"
colnames(g)[3] <- "coefdist"
g<-SpatialPointsDataFrame(coords =cbind(g$long,g$lat),data = g, 
proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 
+towgs84=0,0,0"))
g<-spTransform(g,CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 
+towgs84=0,0,0"))
neighsp<-spTransform(neighbourhood,CRS("+proj=longlat +datum=WGS84 
+ellps=WGS84 +towgs84=0,0,0"))
mapdata1 <- as.data.frame(g)
mapdata2<- fortify(neighsp, region ="NOM")
#Map
gwr.point1<-ggplot(mapdata1, aes(x=long,y=lat))+
geom_point(aes(colour=coefdist))+
scale_colour_gradientn(colours = terrain.colors(100), 
guide_legend(title="Coefs"))
gwr.point1+geom_polygon(data=mapdata2, aes(group=group), 
colour="grey",fill = "white",alpha = 1/3)

neighborhood_forcertified位于UTM坐标中,而logairbnb位于地理坐标中。

你应该改造其中一个。由于它们是数据帧(正如您在评论中所说(,您必须首先转换为sf对象,然后转换其中一个对象中的坐标:

logairbnb_geo <- st_as_sf(logairbnb, coords = c("x", "y"), crs=4326)
neigh_geo <- st_as_sf(neighbourhood_fortified, coords = c("long", "lat"), crs=25831)
neigh_geo <- st_transform(neighbourhood_fortified, st_crs(logairbnb))

然后可以使用geom_sf绘制它们:

ggplot()+
geom_sf(data=neigh_geo, fill = "white", colours = 
terrain.colors(10)))+
geom_sf(data=logairbnb_geo, mapping=aes(colour=coefdist_center))+
scale_colour_gradientn(colours = terrain.colors(10), 
guide_legend(title="Coefs"))+
coord_equal()

注意:我根据你的绘图坐标使用了最可能的crs,你应该在数据源中检查正确的crs。

注2:我没有测试代码块,因为我没有你的数据。

最新更新