0

I have a beginners question in R. I have a data frame (that contains data on some geographical regions) and I have a corresponding shapefile for those regions. I would like to plot the data from the data frame onto the geometry.

Looking at some examples in textbooks and online, e.g. in the sf package, it seems that the geometry data needs to be converted into multi-polygons rather than kept in the shapefile format.

My question is how does one convert a shapefile into the multi-polygon geometry data so that the data can be plotted? Does it need to be converted, and if not, is there another way?

I apologise for lack of code, but I don't quite know where to start.

user1778351
  • 143
  • 7

1 Answers1

0

It used to be necessary to convert shapefiles to polygons to make them usable for ggplot; the method was ggplot2::fortify(). This method is still valid (in meaning it was not descoped from current ggplot version).

But while this was necessary (note the past tense) and while you can still find a lot of oldish materials describing the process it is no longer required. Nor is it current best practice.

Since ggplot 3.0.0 (released in July 2018) ggplot has support for sf, and the best practice for visualizing spatial data ("shapefiles") in ggplot is ggplot2::geom_sf() which requires no prior conversion.

The best part is that shapefiles in context of {sf} package are also data frames - meaning that you can use standard data frame manipulating tools (such as dplyr::left_join()) to join a dataframe with data information (e.g. data per some administrative units) to a dataframe with spatial information (e.g. polygons of the administrative units)

Jindra Lacko
  • 7,814
  • 3
  • 22
  • 44