Norhther
Norhther

Reputation: 500

Strange geospatial plot with ggplot2

I'm trying to plot Spain with each country, so I'm using a .geojson from github. My code is the following:

library(tidyverse)
library(geojsonio)
spdf <- geojson_read("https://raw.githubusercontent.com/codeforamerica/click_that_hood/master/public/data/spain-provinces.geojson",  what = "sp")

library(broom)
spdf_fortified <- tidy(spdf, region = "cod_prov")

ggplot() +
  geom_polygon(data = spdf_fortified, aes( x = long, y = lat, group = id), fill="white", color="grey") +
  theme_void() +
  coord_map()

And the output is really erratic, the polygons are really messed.

enter image description here

Hi have some questions regarding it. First of all, why this behaviour?

Also reading some tutorials I found that we need to "fortify" the spdf, why's that?

And finally, what does group is doing here?

Upvotes: 2

Views: 105

Answers (1)

Brian
Brian

Reputation: 8275

I don't think you need to do any data processing steps, if you just directly read the GeoJSON in using the {sf} package, which is also well-integrated to {ggplot2} graphics.

library(sf)
#> Linking to GEOS 3.7.2, GDAL 2.4.2, PROJ 5.2.0
library(ggplot2)

spain <- read_sf("https://raw.githubusercontent.com/codeforamerica/click_that_hood/master/public/data/spain-provinces.geojson") 

ggplot() +
  geom_sf(data = spain)

Created on 2020-05-03 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions