对于我的学校作业,我试图制作荷兰地图,其中填充的颜色标度取决于整数(公民数量).我有一个名为mun_neth的数据集,它是一个SpatialPolygonDataFrame,包含荷兰的所有多边形和我想要绘制的所有数据.我尝试了三种不同的方法,我在下面添加了这些方法.我还把错误消息放在下面.我想我误解了填充要求.哪里出错了,我该如何解决?
在stackoverflow上搜索之后,我觉得我已经非常接近绘制地图了.但遗憾的是它尚未发挥作用.
# Set workspace
getwd()
setwd("~/Wageningen/2.2 Geoscripting/data")
# Load libraries
install.packages("RCurl", dependencies=TRUE)
library(RCurl)
install.packages("ggplot2", dependencies=TRUE)
library(ggplot2)
install.packages("rgdal", dependencies=TRUE)
library(rgdal)
# Load in data
dl_from_dropbox <- function(x, key) {
require(RCurl)
bin <- getBinaryURL(paste0("https://dl.dropboxusercontent.com/s/", key, "/", x),
ssl.verifypeer = FALSE)
con <- file(x, open = "wb")
writeBin(bin, con)
close(con)
message(noquote(paste(x, "read into", getwd())))
}
dl_from_dropbox("Netherlands.zip", "bocfjn1l2yhxzxe")
unzip("Netherlands.zip")
mun_neth <- readOGR('gem_2012_v1.shp', layer = 'gem_2012_v1')
# First attempt
mun_neth <- readOGR('gem_2012_v1.shp', layer = 'gem_2012_v1')
mun_neth@data$id <- rownames( mun_neth@data )
mun_neth.df <- as.data.frame( mun_neth )
mun_neth.fort <- fortify( mun_neth , region = "id" )
mun_neth.gg <- join( mun_neth.fort , mun_neth.df , by = "id" )
ggplot(data = mun_neth, aes(long, lat, group=group)) +
geom_map(aes(fill = mun_neth$AANT_INW, color = category), map =mun_neth.gg) +
scale_fill_gradient(high = "red", low = "white", guide = "colorbar")
scale_colour_hue(h = c(120, 240))
Run Code Online (Sandbox Code Playgroud)
为每个多边形定义的区域
错误:无法分配大小为9.5 Mb的向量
# second attempt
ggplot(mun_neth$AANT_INW, aes(x=T_MEAN))
Run Code Online (Sandbox Code Playgroud)
错误:ggplot2不知道如何处理类整数的数据
# Third attempt
ggplot(aes(x=x,y=y,fill=AANT_INW),data=mun_neth)
Run Code Online (Sandbox Code Playgroud)
为每个多边形定义的区域
错误:绘图中没有图层
假设已经下载了shapefile,您可以执行以下操作.它可能需要在美容方面进行一些整理,但作为第一个近似似乎没问题.
library(rgdal)
library(ggplot2)
work.dir <- "your_work_dir"
mun.neth <- readOGR(work.dir, layer = 'gem_2012_v1')
mun.neth.fort <- fortify(mun.neth, region = "AANT_INW")
mun.neth.fort$id <- as.numeric(mun.neth.fort$id)
mun.neth.fort$id <- mun.neth.fort$id/1000 # optionally change to thousands?
mun.neth.fort[mun.neth.fort$id <= 0, 'id'] <- NA # some areas not numerically valid,
# presumably water zones
ggplot(data = mun.neth.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon(colour = "black") +
coord_equal() +
theme()
Run Code Online (Sandbox Code Playgroud)