R - using data of shapefiles/SpatialPolygonsDataFrame to colour/fill ggplots

99封情书 提交于 2020-04-11 08:53:13

问题


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.


回答1:


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))



回答2:


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.



来源:https://stackoverflow.com/questions/19025898/r-using-data-of-shapefiles-spatialpolygonsdataframe-to-colour-fill-ggplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!