【发布时间】:2016-07-04 01:19:03
【问题描述】:
我正在尝试使用ggplot2 绘制美国人口普查数据。我能够绘制特定年份(所有州)的数据并使用正确的数据生成地图。当我尝试将几年结合起来分析一段时间内的趋势时,fortify 和 facet_wrap 都出现错误。
当我在将多年合并到 @dataof 空间对象后使用 fortify 时,我收到此错误:
maptools::unionSpatialPolygons(cp, attr[, region]) 中的错误: 输入长度不同
我尝试实施此 stackoverflow 问题中提供的解决方案 Drawing maps based on census data using ggplot2 但这似乎对我不起作用。
由于我不确定在fortify 中使用region="id" 的目的,所以我使用了没有它的函数。 Fortify 工作正常,但我遇到了Facet_Wrap() 的输出问题。我似乎面临与该用户R, Incorrect output from ggplot2 and facet_wrap when using spatial data 相同的问题,但问题没有得到解答。
我已按照http://spatial.ly/2013/12/introduction-spatial-data-ggplot2/ 中提到的步骤进行操作,但我无法解决问题
我的代码:
#Import the data from the web and make it tidy. This data includes years from 1900-2000
url<-"http://www.demographia.com/db-state1900.htm"
pop_00<-readHTMLTable(url,which = 1,skip=1,stringsAsFactors=FALSE)
pop_00<-tbl_df(pop_00)
pop_00<-pop_00%>%gather(date,pop,-State)%>%filter(date!="2003")
colnames(pop_00)[1]<-"name"
#Import 2010 data from https://www.census.gov/popest/data/national/totals/2015/files/NST-EST2015-alldata.csv
uspop_10<-read.csv("NST-EST2015-alldata.csv")
poptidy<-tbl_df(uspop_10)
colnames(poptidy)<-tolower(colnames(poptidy))
poptidy<-select(poptidy,c(name,census2010pop))
poptidy<-poptidy%>%gather(date,pop,-name)
poptidy$date<-gsub("census2010pop","2010",poptidy$date)
pop_sub<-rbind(poptidy,pop_00)
pop_sub$pop<-as.numeric(pop_sub$pop)
# Download list of states to filter unwanted rows in the pop_sub table
url_state<-"http://www.columbia.edu/~sue/state-fips.html"
state_fips<-readHTMLTable(url_state,which=1)
pop_sub<-filter(pop_sub,name %in% state_fips$`State or District`)
# Shape file of US https://www.census.gov/geo/maps- data/data/cbf/cbf_state.html
usmap<-readOGR("cb_2014_us_state_500k",layer="cb_2014_us_state_500k")
colnames(usmap@data)<-tolower(colnames(usmap@data))
usmap@data<-left_join(usmap@data,pop_sub,"name")
usmap@data$id <-row.names(usmap@data)
usmap_f<-fortify(usmap,region="id")
usmap_f<-inner_join(usmap_f,usmap@data,"id")
ggplot(usmap_f)+aes(long,lat,group=group,fill=pop/1000)+geom_polygon()+facet_wrap(~date)+coord_map(xlim=c(-150,-50),ylim=c(20,50))+scale_fill_gradient2(low="green",mid="blue",high="red",midpoint=15000,name="Population in Thousands")+geom_path(colour="black", lwd=0.05)
【问题讨论】:
-
编辑:一位用户评论说要求我使用 tidy in bloom 包而不是 fortify。我尝试了一下,并用情节的图像更新了原始帖子,但由于某种原因,他的评论消失了。 Tidy(usmap) 像 fortify(usmap) 一样工作得很好。但是,tidy(usmap,region="id) 给出与 fortify(usmap,region="id) 相同的错误。我不确定问题是什么,希望 soemone 能够提供一些见解。