gpt4 book ai didi

r - 如何在 geom_sf() 中翻转 y 轴?

转载 作者:行者123 更新时间:2023-12-03 16:51:39 27 4
gpt4 key购买 nike

试图结合 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()

ggplot sp geom only
# 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")

ggplot both geoms

带有警告的绘图输出:

Coordinate system already present. Adding new coordinate system, which will replace the existing one.


## 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()

ggplot y reversed

带有警告的绘图输出:

Coordinate system already present. Adding new coordinate system, which will replace the existing one.



使 geom_sf y 坐标反转的建议?

我试过这个:
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()

关于r - 如何在 geom_sf() 中翻转 y 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53620768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com