Open and Plot Geojson files in R



Geojson files are a common way to store geospatial data. This post explains how to read it with R and the sf package, and how to plot it in base R or with ggplot2.

Background map section About Maps

If you did not find the geospatial data you need in existing R packages (see the map section), you need to find this information elsewhere on the web.

It will often be stored as a .geoJSON format. This post explains how to read it.

Find and download a .geoJSON file


You need to dig the internet to find the geoJSON file you are interested in. For instance, this URL provides a file containing french region boundaries.

You can load it in R with:

# Download to a temporary file
tmp_geojson <- tempfile(fileext = ".geojson")
download.file(
  "https://raw.githubusercontent.com/gregoiredavid/france-geojson/master/communes.geojson",
  tmp_geojson
)

# Let's read the downloaded geoJson file with the sf library:
library(sf)
my_sf <- read_sf(tmp_geojson)


That’s it! You now have a geospatial object called my_sf. I strongly advise to read this post to learn how to manipulate it.

Just in case, here is how to plot it in base R and with ggplot2.

Plot it with base R


The basic plot() function knows how to plot a geospatial object. Thus you just need to pass it my_sf and add a couple of options to customize the output.

# Select only the region #6 as you would do with a data frame
my_sf_region_6 <- my_sf[substr(my_sf$code, 1, 2) == "06", ]

par(mar = c(0, 0, 0, 0))
plot(my_sf_region_6$geometry, col = "grey")

Plot it with ggplot2


It is totally possible (and advised IMO) to build the map with ggplot2, using the geom_sf() function as described below.

# Plot it
library(ggplot2)
ggplot(my_sf_region_6) +
  geom_sf(fill = "#69b3a2", color = "white") +
  theme_void()

Related chart types


Map
Choropleth
Hexbin map
Cartogram
Connection
Bubble map



❤️ 10 best R tricks ❤️

👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥