尝试将geom_sf()
与其他某些几何图形组合。我需要反转y轴才能使图正确显示。但是,geom_sf()
似乎忽略了scale_y_reverse()
。
示例:
# install the dev version of ggplot2
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
library(sf)
library(rgeos)
library(sp)
# make triangle
tmpdf <- data.frame(id = 1,
geom = c("LINESTRING(10 10,-10 10,0 0,10 10)"), stringsAsFactors = F)
# read WKT polygons into 'sp' SpatialPolygons object
tmpdf$spgeom <- lapply(tmpdf$geom, FUN = function(x) readWKT(x))
# extract coordinates from the linestring (there has got to be a better way to do this...)
test <- tmpdf[1,"spgeom"]
test2 <- sapply(test, FUN=function(x) x@lines)
test3 <- sapply(test2, FUN=function(x) x@Lines)
test4 <- lapply(test3, FUN=function(x) x@coords)
# plot the sp coordinates
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed()
# make an 'sf' sfc_POLYGON object
tmpdf$sfgeom <- st_as_sfc(tmpdf$geom)
## plot both together, they overlap
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom), color="red")
以警告显示输出:
坐标系已经存在。添加新的坐标系 将替换现有的。
## plot with scale reverse, and everything but the geom_sf flips.
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom), color="red") +
scale_y_reverse()
以警告显示输出:
坐标系已经存在。添加新的坐标系 将替换现有的。
是否建议反转geom_sf y坐标?
我尝试过:
coord_sf(ylim=-(range(st_coordinates(tmpdf$sfgeom)[,"Y"])))
所做的只是改变轴,而不是实际的几何图形。
答案 0 :(得分:1)
啊哈!解决方法:
## get the geom coordinates as data.frame
geomdf <- st_coordinates(tmpdf$sfgeom)
## reverse Y coords
geomdf[,"Y"] <- geomdf[,"Y"]*-1
## re-create geom
tmpdf$sfgeom2 <- st_as_sfc(st_as_text(st_linestring(geomdf)))
## plot the reversed y-coordinate geom:
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom2), color="red") +
scale_y_reverse()