Question

I have a specific question: How can I choose either fill or color of a ggplot according to the data of an SpatialPolygonsDataFrame-object? For example consider the following SpatialPolygonsDataFrame sf:

sf <- readShapePoly("somePolygonShapeFile")

It allows me to access the the example data field FK like:

sf$FK            // or
sf@data$FK

Now, I want to prepare a simple ggplot:

p <- ggplot(sf, aes(x=long, y=lat, group=group, FK=???))

However, I don't know what to pass to FK in aes(). Experiences from gridded data frames (grid.extent(...)) made me think, I could directly put in FK=FK. This does not seem to work for SpatialPolygonsDataFrame-objects. Trying FK=sf$FK or FK=sf@data$FK is not allowed because:

Error: Aesthetics must either be length one, or the same length as the data

I guess, the solution is trivial, but I simply don't get it at the moment.

Was it helpful?

Solution

Thanks to @juba, @rsc and @SlowLearner I've found out, that the installation of gpclib was still missing to be able to give the gpclibPermit. With this done, fortifying sf using a specified region is not problem anymore. Using the explanation from ggplot2/wiki I am able to transfer all data fields of the original shapefile into a plotting-friendly dataframe. The latter finally works as was intendet for plotting the shapefile in R. Here is the final code with the actual workingDir-variable content left out:

require("rgdal") # requires sp, will use proj.4 if installed
require("maptools")
require("ggplot2")
require("plyr")

workingDir <- ""

sf <- readOGR(dsn=workingDir, layer="BK50_Ausschnitt005")
sf@data$id <- rownames(sf@data)
sf.points <- fortify(sf, region="id")
sf.df <- join(sf.points, sf@data, by="id")

ggplot(sf.df,aes(x=long, y=lat, fill=NFK)) + coord_equal() + geom_polygon(colour="black", size=0.1, aes(group=group))

OTHER TIPS

First, you should use the readOGR function from the rgdal library to read your shapefile (then you won't have problems with gpclib). Here is an example of how to do that.

Second, are you trying to pass the sf object to ggplot as-is? If so, you need to use fortify() to convert your spatial object into a data frame. There should be some kind of identifying column in sf@data such as ID or NAME. So try something like:

sf.df <- fortify(df, region = "NAME")

...and use sf.df for plotting using ggplot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top