R 如何在geom_sf()中翻转y轴?
尝试将R 如何在geom_sf()中翻转y轴?,r,ggplot2,sf,R,Ggplot2,Sf,尝试将geom\u sf()与其他一些geom组合。我需要反转y轴以使绘图正确显示。但是,geom\u sf()似乎忽略了scale\u y\u reverse() 例如: # install the dev version of ggplot2 devtools::install_github("tidyverse/ggplot2") library(ggplot2) library(sf) library(rgeos) library(sp) # make triangle tmpdf
geom\u sf()
与其他一些geom组合。我需要反转y轴以使绘图正确显示。但是,geom\u sf()
似乎忽略了scale\u y\u 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()
打印带有警告的输出:
坐标系已存在。添加新的坐标系,该坐标系
将取代现有的
反转几何坐标的建议
我试过这个:
coord_sf(ylim=-(range(st_coordinates(tmpdf$sfgeom)[,"Y"])))
所做的只是改变了轴,而不是实际的几何图形。啊哈!这里有一个解决方法:
## 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()
##获取几何坐标作为data.frame
geomdf不确定,但看起来geom\u sf
只能获取一种坐标()。对我来说,这表明你不能翻转或反转它(没有米西·埃利奥特的参考)。哈。因此,我搜索了st_*函数,它允许我反转y坐标。可能需要一个坐标设定器。以下内容不起作用:st_坐标(tmpdf$sfgeom)[,“Y”]=st_坐标(tmpdf$sfgeom)[,“Y”]*-1
Off-topic,但是这个geom有什么意义,为什么要使用它?可视化对象的空间特征。e、 例如,来自空间数据库、shapefile等。
coord_sf(ylim=-(range(st_coordinates(tmpdf$sfgeom)[,"Y"])))
## 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()