绘制空间普查数据时,fortify() 出错,facet_wrap 输出不正确

Error with fortify() and and incorrect output of facet_wrap when plotting spatial census data

我正在尝试使用 ggplot2 绘制美国人口普查数据。我能够绘制特定年份(所有州)的数据并生成具有正确数据的地图。当我尝试将几年结合起来分析一段时间内的趋势时,fortifyfacet_wrap.

都出现错误

当我在将多年合并到 @dataof 空间对象后使用 fortify 时,我收到此错误:

Error in maptools::unionSpatialPolygons(cp, attr[, region]) : input lengths differ

我尝试实现这个 Whosebug 问题中提供的解决方案 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)

我能找出这里的错误。将 rowid 分配给初始空间数据,然后加入空间数据就可以了。

修改后的代码:

usmap@data$id <-rownames(usmap@data)
usmap@data<-left_join(usmap@data,pop_sub,"name")

#row.names(usmap@data) <- NULL
usmap_f<-fortify(usmap)
usmap_f<-inner_join(usmap_f,usmap@data,"id")

Plot after correction