与R使用shp文件的等值线图

yok*_*ota 4 gis r map ggplot2

你好stackoverflow社区!

有人请帮助我,因为我在R中创建一个等值区域图时遇到了一些困难.截至目前,我已将LL信息分配给我的兴趣点,现在我想使用"cans"变量创建一个等值区域图在高中地区的数据集(data.csv)中(highdist_n83.shp.zip).我想知道的是如何使用每个地区的罐头总和正确填充地图.我提供了代码,它从dropbox和我想要使用的shape文件中提取样本数据文件.

编辑 对不起,我忘了添加,当我只绘制形状文件时,我能够通过ggplot看到它呈现.但是,当我尝试使用"cans"变量的数量"填充"区域时,R会挂起一段时间,然后渲染看起来像原始形状上的大量线条.我想知道错误是否是由于以下可能的原因造成的

  1. 形状文件不好
  2. 可能存在我如何合并数据框和形状文件的问题,因为我注意到合并文件中添加了其他行
  3. 在一个地区有多所学校,我在使用ddply时没有合并.

感谢您的时间!

###load R scripts from dropbox
dropbox.eval <- function(x, noeval=F) {
require(RCurl)
intext <- getURL(paste0("https://dl.dropboxusercontent.com/",x), ssl.verifypeer = FALSE)
intext <- gsub("\r","", intext)
if (!noeval) eval(parse(text = intext), envir= .GlobalEnv)
return(intext)
}

##pull scripts from dropbox 
dropbox.eval("s/wgb3vtd9qfc9br9/pkg.load.r")    
dropbox.eval("s/tf4ni48hf6oh2ou/dropbox.r")

##load packages
pkg.load(c(ggplot2,plyr,gdata,sp,maptools,rgdal,reshape2))

###setup data frames
dl_from_dropbox("data.csv","dx3qrcexmi9kagx")
    data<-read.csv(file='data.csv',header=TRUE)

###prepare GIS shape and data for plotting
dropbox.eval("s/y2jsx3dditjucxu/dlshape.r")     
temp <- tempfile()
dlshape(shploc="http://files.hawaii.gov/dbedt/op/gis/data/highdist_n83.shp.zip", temp)
shape<- readOGR(".","highdist_n83") #HDOE high school districts  
shape@proj4string 

shape2<- spTransform(shape, CRS("+proj=longlat +datum=NAD83"))

data.2<-ddply(data, .(year, schoolcode, longitude, latitude,NAME,HDist,SDist), summarise,
        total = sum(total),
        cans= sum(cans))

coordinates(data.2) <-~longitude + latitude
shape2.df<-fortify(shape2)
mshape2.df<- merge(shape2.df,shape2@data, by.x="id", by.y="ID",all=TRUE)

newdata <- merge(mshape2.df,data.2, by.x="NAME", by.y="NAME", all=TRUE)
newdata  <- newdata [order(newdata $order),]

###choropleth map: 
mapPlot <- ggplot(newdata,aes(x=long, y=lat,drop=FALSE)) +
geom_polygon(aes(fill=cans, drop=FALSE), colour = "black", lwd = 1/9,na.rm=FALSE)
+ ggtitle("Total of Cans Across State")
print(mapPlot)
Run Code Online (Sandbox Code Playgroud)

Sim*_*lon 7

强化shapefile时,最终会出现错误的ID.而是,根据shapefile的行名显式添加ID列,并使用它进行合并.您也没有告诉geom_polygon如何对行中的行进行分组,data.frame因此它们都被绘制为一个连续重叠的自相交多边形.添加组参数geom_polygon.我也想用RColorBrewer它为地图选择漂亮的颜色(使用该功能brewer.pal).

试试这个:

require(RColorBrewer)
shape2@data$id <- rownames(shape2@data)
sh.df <- as.data.frame(shape2)
sh.fort <- fortify(shape2 , region = "id" )
sh.line<- join(sh.fort, sh.df , by = "id" )


mapdf <- merge( sh.line , data.2 , by.x= "NAME", by.y="NAME" , all=TRUE)
mapdf <- mapdf[ order( mapdf$order ) , ]

ggplot( mapdf , aes( long , lat ) )+
  geom_polygon( aes( fill = cans , group = id ) , colour = "black" )+
  scale_fill_gradientn( colours = brewer.pal( 9 , "Reds" ) )+
  coord_equal()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述