R-使用shapefile/SpatialPolygonsDataFrame的数据为ggplots上色/填充 [英] R - using data of shapefiles/SpatialPolygonsDataFrame to colour/fill ggplots

查看:196
本文介绍了R-使用shapefile/SpatialPolygonsDataFrame的数据为ggplots上色/填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具体的问题:如何根据SpatialPolygonsDataFrame对象的数据选择ggplot的填充或颜色?例如,考虑以下SpatialPolygonsDataFrame sf:

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

它允许我访问示例数据字段FK,例如:

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

sf$FK            // or
sf@data$FK

现在,我想准备一个简单的ggplot:

Now, I want to prepare a simple ggplot:

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

但是,我不知道在aes()中将什么传递给FK.来自网格数据帧(grid.extent(...))的经验使我想到,我可以直接输入FK = FK.这似乎不适用于SpatialPolygonsDataFrame对象.不允许尝试FK = sf $ FK或FK = sf @ data $ 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.

推荐答案

感谢@ juba,@ rsc和@SlowLearner,我发现仍然缺少gpclib的安装才能提供gpclibPermit.完成此操作后,使用指定区域加强sf不再是问题.使用 ggplot2/wiki 中的说明,我可以传输所有数据字段将原始shapefile转换为易于打印的数据框.后者最终像在R中绘制shapefile的意图一样工作.这是最后的代码,其中省略了实际的workingDir变量内容:

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

这篇关于R-使用shapefile/SpatialPolygonsDataFrame的数据为ggplots上色/填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆