用sf包替代fortify绘制地图

问题描述 投票:0回答:1

我想绘制地图。早期的时候一切都还好,但是由于没有

rgdal
maptools
,有些功能似乎没有替代品。对我来说就是
fortify
的情况;我尝试了
tidy
和其他功能但没有成功。

In my example:

#----------------------------------------------------
# Map representation
library(sf)
library(ggplot2)

url <- "https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/f3fde312c9b816dff3994f39f2bcda03209eff8f/continents.json"
stop_for_status(GET(url, write_disk("continents.json")))
continents <- geojson_sf("continents.json")
continents.f <- continents[continents$CONTINENT %in% c("North America", "Central America", "South America"),]
continents_map <- fortify(continents.f, region="CONTINENT")


gg <- ggplot() # the base map
gg <- gg + geom_map(data=continents_map, map=continents_map,
                    aes(x=long, y=lat, map_id=id, group=group),
                    fill="#ffffff", color="black", size=0.15) +
                    lims(x = c(-110, -20), y = c(-60, 20))
gg 
#---------------------------------------------------- 

Error in `geom_map()`:
! `map` must have the columns `x`, `y`, and `id`
Run `rlang::last_trace()` to see where the error occurred.

请问有什么帮助吗?

r ggplot2 geospatial spatial
1个回答
0
投票

只需从

read_sf()
包中使用
sf
加载数据即可,不需要
fortify()
。建议在加载geojson数据时使用
geom_sf()
来绘制地图。

library(sf)
library(ggplot2)

continents <- read_sf("https://gist.githubusercontent.com/hrbrmstr/91ea5cc9474286c72838/raw/f3fde312c9b816dff3994f39f2bcda03209eff8f/continents.json")
continents.f <- continents[continents$CONTINENT %in% c("North America", "Central America", "South America"),]

ggplot(data = continents.f) +
  geom_sf(fill="#ffffff", color="black", size=0.15) +
  lims(x = c(-110, -20), y = c(-60, 20))


# add some values to fill
continents.f$test <- 1:nrow(continents.f)
ggplot(data = continents.f) +
  geom_sf(aes(fill = test)) +
  lims(x = c(-110, -20), y = c(-60, 20))
© www.soinside.com 2019 - 2024. All rights reserved.