英文:
trouble plotting shapefiles in R with geom_sf
问题
我尝试在R中使用ggplot2
和sf
绘制shapefiles,使用geom_sf
,但它引发了我无法解决的错误。我可以使用plot()
绘制SpatialPolygonsDataFrame,但如果可能的话,我想使用ggplot
和geom_sf
。
这些shapefiles可以在这里找到:https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Neighborhoods/bbvz-uum9
以下是应该是一个MWE:
library(ggplot2)
library(sf)
library(rgdal)
nbrhd_shp <- readOGR(dsn = shapefile_filepath, layer = "geo_export_00bf6ede-a61b-4746-8c69-e1510a184344")
class(nbrhd_shp)
plot(nbrhd_shp)
这两个都有效。class(nbrhd_shp)
返回如预期的那样:
> class(nbrhd_shp)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
但当我尝试使用ggplot
绘制时,我得到一个空白图并且有坐标标签在坐标轴上以及一个错误消息:
ggplot(nbrhd_shp) +
geom_sf(data = nbrhd_shp@data, aes(geometry = nbrhd_shp@polygons))+
coord_sf(crs = st_crs(nbrhd_shp))
为每个Polygons定义的Regions
警告信息:
在`stat_sf()`中计算失败
由`UseMethod()`中的错误引起:
! 对类为 "list" 的对象应用 "st_bbox" 的方法
英文:
I'm trying to plot shapefiles in R using ggplot2
and sf
to call geom_sf
but it's throwing errors that I can't seem to work around. I am able to plot the SpatialPolygonsDataFrame without issue using plot()
but I'd like to work with ggplot
and geom_sf
if possible.
The shapefiles can be found here: https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Neighborhoods/bbvz-uum9
Here's what should be a MWE:
library(ggplot2)
library(sf)
library(rgdal)
nbrhd_shp <- readOGR(dsn = shapefile_filepath, layer = "geo_export_00bf6ede-a61b-4746-8c69-e1510a184344")
class(nbrhd_shp)
plot(nbrhd_shp)
these both work. The class(nbrhd_shp)
returns as expected:
> class(nbrhd_shp)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
But when I try to plot with ggplot
I get a blank plot with coordinate labels on the axes and an error message:
ggplot(nbrhd_shp) +
geom_sf(data = nbrhd_shp@data, aes(geometry = nbrhd_shp@polygons))+
coord_sf(crs = st_crs(nbrhd_shp))
Regions defined for each Polygons
Warning message:
Computation failed in `stat_sf()`
Caused by error in `UseMethod()`:
! no applicable method for 'st_bbox' applied to an object of class "list"
答案1
得分: 0
我认为你应该首先将其转换为 sf 对象。
nbrhd_shp <- st_as_sf(nbrhd_shp)
ggplot(nbrhd_shp) + geom_sf()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论