R post-merge ggplot/qmap plots zipcode polygons incorrectly (jagged)

旧街凉风 提交于 2019-12-11 09:05:59

问题


I have spent days searching this site and others for a solution, and haven't found it yet. If there is another page with my solution, and I missed it, I apologize.

I found this but reloading ggplot2 and rgdal (after detaching) didn't fix it.

I am using demographic data at the ZCTA (zip code tabulation area) to overlay polygons on a Google terrain map. I am able to get the polygons plotted correctly using qmap, but after I merge in the demographic data, the plots are all wrong. I've tried specifying the order, and playing with the merge. (Heck, I've tried all sorts of things.) I'd love some help with this.

is a working plot, before the merge, and

is after.

Here's my code:

# shapefile from Census
fips34 <-readOGR(".", "zt34_d00", stringsAsFactors = FALSE)

# zip code areas, 1 row per ZCTA with nonmissing Census data
ptInd <-read.dta("ptIndzcta.dta")

keepzips <- fips34
keepzips@data$id <-rownames(keepzips@data) # create idvar to remerge
keepzipsdat <- fortify(keepzips, region="id") # fortify
keepzipsdat <- keepzipsdat[order(keepzipsdat$order),] # clarify order
keepzipsdat <- join(keepzipsdat, keepzips@data, by="id") # remerge for zcta

qmap("new jersey", zoom = 8, maptype="terrain", color="bw") +
     geom_polygon(aes(x=long, y=lat, group=group), 
           data=keepzipsdat) + coord_equal() # this map plots fine

# now merge in data to create choropleth
zip2 <- merge(keepzipsdat, ptInd, by.y="zcta5", by.x="ZCTA", all.x = TRUE)
zip2[order(zip2$order),] # reestablish order, is this necessary?

qmap("new jersey", zoom = 8, maptype="terrain", color="bw") +
    geom_polygon(aes(x=long, y=lat, group=group), 
           data=zip2) + coord_equal() # this looks crazy
ggplot(data=zip2, aes(x=long, y=lat, group=group)) + geom_polygon() 
# also crazy

# and this is before assigning a fill variable to the polygons

来源:https://stackoverflow.com/questions/32825786/r-post-merge-ggplot-qmap-plots-zipcode-polygons-incorrectly-jagged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!