Successor to ggplot2::fortify

Hugh picture Hugh · Dec 31, 2015 · Viewed 10.8k times · Source

In the most recent version of ggplot2, ?fortify returns:

Description

Rather than using this function, I now recomend using the broom package, which implements a much wider range of methods. fortify may be deprecated in the future.

The broom package indeed offers many alternatives (such as augment). Which one should be used in what circumstances?

I am particularly interested in an alternative to fortify(spdf) where spdf is a SpatialPolygonsDataFrame.

Answer

Roman Luštrik picture Roman Luštrik · Dec 31, 2015

Here's how I approached the subject.

After searching "broom cran" I was redirected to the corresponding page of the package on CRAN. It offers a few vignettes so I checked out Introduction to broom. After failing to find any string matching "spatial" I closed the PDF and opened the reference manual. Searching for "spatial" I got 7 hits, with the first one on the topic of sp_tidiers. Function tidy is advertised to convert a spatial object to a data.frame. Let's try it.

library(sp)
Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)

Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
x = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)

library(broom)

tidy(x)

   long lat order  hole piece  group   id
1     2   2     1 FALSE     1   s1.1   s1
2     1   4     2 FALSE     1   s1.1   s1
3     4   5     3 FALSE     1   s1.1   s1
4     4   3     4 FALSE     1   s1.1   s1
5     2   2     5 FALSE     1   s1.1   s1
6     5   2     1 FALSE     1   s2.1   s2
7     2   2     2 FALSE     1   s2.1   s2
8     4   3     3 FALSE     1   s2.1   s2
9     5   2     4 FALSE     1   s2.1   s2
10    4   5     1 FALSE     1 s3/4.1 s3/4
11   10   5     2 FALSE     1 s3/4.1 s3/4
12    5   2     3 FALSE     1 s3/4.1 s3/4
13    4   3     4 FALSE     1 s3/4.1 s3/4
14    4   5     5 FALSE     1 s3/4.1 s3/4
15    5   4     6  TRUE     2 s3/4.2 s3/4
16    5   3     7  TRUE     2 s3/4.2 s3/4
17    6   3     8  TRUE     2 s3/4.2 s3/4
18    6   4     9  TRUE     2 s3/4.2 s3/4
19    5   4    10  TRUE     2 s3/4.2 s3/4