代码不适用于其他shp文件 [英] code not working for other shp files
问题描述
在这里,已经解决了,但不知何故,它不适用于不同的shp文件。任何想法为什么?
我一直在尝试使用来自根据给定的变量使用ggplot着色状态(第一个链接)
代码:
库(maptools)
库(ggplot2)
download.file(http://geocommons.com/overlays/ 204743.zip,destfile =204743.zip)
dir.create(ind)
unzip(204743.zip,exdir =ind)
india& - readShapeSpatial(ind / india_state.shp)
f_india< - fortify(india)
i< - sapply(india @ data $ NAME,function(x)agrep(x,data $ Row。标签,max.distance = .3,ignore.case = T)[1])$ b $ b india @ data $ maj< - data $ MAJORITY [i]
f_india< - merge(x = f_india ,y = india @ data,by.x =id,by.y =ID)
ggplot(f_india,aes(x = long,y = lat,group = group,fill = maj)) +
geom_polygon(color =black)
ut:
任何帮助将不胜感激。
您的合并是每行匹配更多不止一次,在数据中创建重复的行。另外还有一个排序问题,当没有匹配的行时,你会丢失多边形。
替换
f_india< - merge(x = f_india,y = india @ data,by.x =id,by.y =ID)
与
f_india< merge(x = f_india,y = unique(india @ data),by.x =id,by.y =ID,all.x = T)
f_india< - f_india [with(f_india ,订单(id,order)),]
编辑: p>
这是我得到的输出。灰色多边形是由不匹配的名称引起的,但这是我唯一可以看到的问题。
The question posed in here , has been solved but somehow it is not working for a different shp file. Any idea why? I have been trying with the shp file from Coloring the states according to a given variable using ggplot (the first link)
Code:
library(maptools)
library(ggplot2)
download.file("http://geocommons.com/overlays/204743.zip", destfile="204743.zip")
dir.create("ind")
unzip("204743.zip", exdir="ind")
india <- readShapeSpatial("ind/india_state.shp")
f_india <- fortify(india)
i <- sapply(india@data$NAME, function(x) agrep(x, data$Row.Labels, max.distance=.3, ignore.case=T)[1])
india@data$maj <- data$MAJORITY[i]
f_india <- merge(x=f_india, y=india@data, by.x="id", by.y="ID")
ggplot(f_india, aes(x=long, y=lat, group=group, fill=maj)) +
geom_polygon(colour="black")
Wrong output:
Any help would be appreciated.
Your merge is matching each row more than once, creating duplicate rows in the data. Additionally there is an ordering problem, and you lose polygons when there isn't a matching row.
Replace
f_india <- merge(x=f_india, y=india@data, by.x="id", by.y="ID")
with
f_india <- merge(x=f_india, y=unique(india@data), by.x="id", by.y="ID",all.x=T)
f_india <- f_india[with(f_india, order(id, order)), ]
EDIT:
Here's the output I get. The grey polygons are caused by mismatched names, but this is the only issue I can see.
这篇关于代码不适用于其他shp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!