我从 here 询问过同样的问题和 here ,但仍然无法解决我的问题。我认为我需要提出整个问题并寻求帮助,而不是将其分解为小部分。
我有一个数据框,我将它导出到 csv,可以在 http://pastebin.com/SNT9Ykt7 找到.
chart <- ggplot(data=map.shp,aes(x=long,y=lat))
### PART1 START ###
chart <- chart + geom_polygon(data=map.shp,aes(x=long,y=lat,group=id),colour=rgb(162,159,140,maxColorValue=255),fill=rgb(233,235,232,maxColorValue=255),size=0.1)
### PART1 END ###
### PART2 START ###
map.group <- unique(map.shp[,"group"])
for (loop in (1:length(map.group))) {
temp.shp <- map.shp[map.shp[,"group"]==map.group[loop],]
temp.colour <- "red"
if (unique(temp.shp[,"hole"])=="TRUE") {
temp.colour <- "blue"
}
chart <- chart + geom_polygon(data=temp.shp,aes(x=long,y=lat,group=id,order=group),colour=rgb(162,159,140,maxColorValue=255),fill=temp.colour,size=0.1)
}
### PART2 END ###
chart <- chart + opts(panel.background=theme_rect(colour=rgb(190,225,247,maxColorValue=255),fill=rgb(190,225,247,maxColorValue=255)),
panel.grid.major=theme_blank(),
panel.grid.minor=theme_blank(),
panel.border=theme_blank(),
plot.background = theme_blank(),
axis.line=theme_blank(),
axis.text.x=theme_blank(),
axis.title.x=theme_blank(),
axis.text.y=theme_blank(),
axis.title.y=theme_blank(),
axis.ticks=theme_blank())
chart <- chart + coord_cartesian(xlim = range(map.shp[,"long"]), ylim = range(map.shp[,"lat"]))
PART1 脚本给了我这个输出:
PART2 脚本给了我这个输出:
实际上这是一 block 带有一些洞的土地,我将在该层下显示其他内容,因此我必须将洞显示为“洞”,因此无法使用 PART2 脚本显示。但是 PART2 脚本正确地绘制了 map (红色为土地,蓝色为洞)。
我需要修复的 PART1 输出中的一些问题:
- 孔的某些部分未显示为孔
- 多边形外的线绘制错误
我不知道我在 PART1 中做错了什么。有人可以帮忙吗?
更新01
txt 文件是使用以下代码创建的:
map.shp.raw <- readShapeSpatial("shp_files/map.shp")
map.shp <- fortify(map.shp.raw)
附加的txt文件可以保存为txt并使用read.table命令导入为data.frame。
最佳答案
向@spacedman 点头,他说:
The solution I came up with years ago for drawing holes is to make sure that after each hole your x,y coordinates return to the same place. This stops the line buzzing all around and crossing other polygons and leaving open areas that the winding number algorithm doesn't fill (or does fill when it shouldn't).
(在 https://stackoverflow.com/a/12051278/602276 中)
所以,让我们听从他的建议吧:
library(plyr2)
map.shp2 <- ddply(map.shp, .(piece), function(x)rbind(x, map.shp[1, ]))
ggplot(data=map.shp2) + geom_polygon(aes(x=long,y=lat))
关于r - 使用 ggplot2 绘制带孔的土地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12047919/