[R-sig-Geo] Plotting simple features sf with ggplot2

Michael Sumner mdsumner at gmail.com
Wed Dec 7 23:43:48 CET 2016


On Thu, Dec 8, 2016, 04:21 Edzer Pebesma <edzer.pebesma at uni-muenster.de>
wrote:



On 07/12/16 17:49, Manuel Spínola wrote:
> Dear list members,
>
> Is there a way to plot a simple features (sf) multipolygon (imported
> shapefile) using ggplot2?

Short answer is: not yet, I'm waiting for some help on this.

There has been quite some discussion about this issue here:

https://github.com/edzer/sfr/issues/88
>
> Similar to plotting a SpatialPolygonDataFrame  with ggplot2 using the
> function fortify first to convert the SPDF to a data frame.
>

I think there is now a majority opinion that fortify is not such a good
idea for simple feature (or in general: spatial) geometries.


It's not a great idea, but you can do it and it already works.

- it treats a layer as a set of grouped coordinates, rather than as
separate objects

- it wastes memory, by copying identifying attributes from the nested list
hierarchy to each coordinate

- it can't work with mixed topology types (lines and polys for example)

- it's not supported

Why not leverage the existing sp-fortify method by casting to Spatial?

library(sf)

## from ?st_read

nc <- st_read(system.file("shape/nc.shp", package="sf"), "nc", crs = 4267)

## a unique ID?

length(unique(nc$NAME)) == nrow(nc)
library(ggplot2)
nc_f <- fortify(as(nc, "Spatial"), region = "NAME")
ggplot(nc_f) + aes(x = long, y = lat, group = group, fill = id) +
ggpolypath::geom_polypath() + guides(fill = FALSE)


There are non-sp ways to do this, but none that are stable yet. Using
ggpolypath ensures that holes will work, but if you don't need holes
geom_polygon is fine.

Let me know if you have problems getting what you want, but please provide
reproducible examples.  It's not easy to navigate here, there are many
traps and it's easy to get it wrong.

(While the integrated  sf-ggplot2-geom will be awesome, it will be be
embedded within a plot-only context, and I want those idioms available
independently, and for going beyond simple features. )

Cheers, Mike.




--
Edzer Pebesma
Institute for Geoinformatics  (ifgi),  University of Münster
Heisenbergstraße 2, 48149 Münster, Germany; +49 251 83 33081
<+49%20251%208333081>
Journal of Statistical Software:   http://www.jstatsoft.org/
Computers & Geosciences:   http://elsevier.com/locate/cageo/

_______________________________________________
R-sig-Geo mailing list
R-sig-Geo at r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

-- 
Dr. Michael Sumner
Software and Database Engineer
Australian Antarctic Division
203 Channel Highway
Kingston Tasmania 7050 Australia

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list