r - 无法将 topojson 读入 R 以便使用 ggplot2 和 sp 进行绘图

标签 r ggplot2 r-sf r-sp topojson

我正在尝试将 topojson 读入 R 中以供 ggplot2 使用。看来 rgdal 包即将退役,所以我尝试在 sp 包中使用 st_read,但我只是得到一个大盒子就这样。看起来我得到的字段是正确的,但它绝对没有正确地将整个内容放在那里。它说它只有一个功能和两个字段。知道我可能做错了什么吗?谢谢。

我尝试按照这些指示操作,但似乎没有任何效果:

R - Import html/json map file to use for heatmap https://www.r-bloggers.com/2014/09/overcoming-d3-cartographic-envy-with-r-ggplot/

我可以给出一个示例文件——我知道它有效,因为我们确实使用它并且能够使用 D3 显示它,但我希望能够使用 ggplot2 显示它。

不起作用的示例代码:

library(ggplot2)
library(sp)

j <- sf::st_read("mytopo.json")

ggplot() +
  geom_sf(aes(fill = iso_a3), j) +
  coord_sf()

j <- geojsonio::topojson_read("mytopo.json")

ggplot() +
  geom_sf(aes(fill = iso_a3), j) +
  coord_sf()

注意:出于安全原因删除了示例的链接。

最佳答案

mapshaper.org 的帮助下可以在 R 中打开这些文件。我用的是在线上传,但是有一个command line tool也是如此。

使用mapshaper 将文件导出为shapefile。可能有一些选项可以纠正 R 难以处理的几何形状,但我不熟悉 Mapshaper 及其选项。下面的代码很好地解决了 R 中无效几何图形的问题。通过 Mapshaper 转换后,您将拥有一个包含 .dbf、.shp 和 .shx 文件的文件夹,R 的 sf 包可以使用这些文件阅读。

library(dplyr)
library(sf)
library(ggplot2)

my_sf <- st_read('path/to/shapefile/folder/')
#> Reading layer `00005f8d4076b8ced__' from data source `path/to/shapefile/folder/' using driver `ESRI Shapefile'
#> Simple feature collection with 218 features and 1 field (with 3 geometries empty)
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 0 ymin: 0 xmax: 940 ymax: 470
#> CRS:           NA

# But some geometries are not valid (only showing first 3 rows)
st_is_valid(my_sf[1:3,])
#> [1]  TRUE FALSE FALSE

# Fixing the invalid geometries taken from:
#  https://r-spatial.org/r/2017/03/19/invalid.html#making-invalid-polygons-valid

valid <- st_is_valid(my_sf)
my_sf_valid <- st_buffer(my_sf[!is.na(valid),], 0.0)

ggplot(my_sf_valid) +
  geom_sf()

map 显示但被翻转。这里有一个关于此的 gis 堆栈问题:https://gis.stackexchange.com/a/233792/161721

这可能与 Mapshaper 翻转 .svg/topojson 文件的坐标有关

width= (SVG/TopoJSON) Set the width of the output dataset in pixels. When used with TopoJSON output, this option switches the output coordinates from geographic units to pixels and flips the Y axis. SVG output is always in pixels (default SVG width is 800).

以上引用自:https://github.com/mbloch/mapshaper/wiki/Command-Reference

reprex package 于 2022 年 3 月 18 日创建(v2.0.1)

关于r - 无法将 topojson 读入 R 以便使用 ggplot2 和 sp 进行绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71521568/

相关文章:

r - 找到数据框中变量更改其值的位置

r - 当假设不满足时如何避免单根函数停止?

r - 如何操作facet_grid图的 strip 文本?

r - 将线图例添加到 geom_sf

r - 使用火车时出现插入符错误 : "Something is wrong; all the RMSE metric values are missing"

r - 如何从图中删除顶点并在其邻居之间创建边?

r - ggplot : How to add a certain percentage to the top of the pillars of a histogram

r - 带有 geom_segment 的 x 轴顺序

r - 在地理空间分析中将多多边形转变为单点

r - 如何在R中计算国家之间的边界长度?