Error while producing choropleth map with maptoools

474 views Asked by At
Hello, I am new to GIS with R and have been trying to create a choropleth map. I successfully created a choropleth map with ggplot2 and the fortify function, but it is not that easy to add more layers on the top of a map with ggplot2. Instead I am using maptools to plot a choropleth map and later add more layers as needed for my analysis. The choropleth map I am trying to plot is the level of unemployment for Allegheny county by census tract. the files are available here: shapefile https://www.dropbox.com/s/uci5g2ekeq9niww/census%20tract%20allegheyny%202010.shp csv file https://www.dropbox.com/s/6nq8nnxftot8iya/allegheyny%20socioeconomic%20info.csv And here is my code
library(rgdal)
library(RArcInfo)
library(RColorBrewer)
library(maptools)
library(maps)
library(classInt)
we load the csv file, clean it and create a subset with Id2 and unemployment
data<- read.csv('allegheyny socioeconomic info.csv',dec='.',
                header=T)
data$Id2<-as.numeric(as.character(data$Id2))
data$Percent.Unemployed<-as.numeric(as.character(data$Percent.Unemployed))
names(data)[names(data)=="Percent.Unemployed"]<-'unemployed'
data1<-subset(data, select= c('Id2', 'unemployed'))
load shapefile of Allegheny County census tracts for 2010
tracts<-readShapePoly("census tract allegheyny 2010.shp")
names(tracts)[names(tracts)=="GEOID10"]<-'Id2'

merge the data by Id2

tr1<-merge(data1,tracts)                     
sort(tr1$Id2)
colours<-brewer.pal(5, 'Greens')
breaks<- classIntervals(tr1$unemployed, n=5, style='sd')
plot(tr1, col=colours[findInterval(tr1$unemployed, breaks, all.inside=T), axes=F])
And this is the message I get:
Error in x[-1L] >= x[-n] : comparison of these types is not implemented
1

There are 1 answers

6
jlhoward On BEST ANSWER
plot(tracts,col=colours[findInterval(tr1$unemployed, breaks$brks, all.inside=T)])

Produces this:

To answer your question specifically:

The reason for the error is that findInteerval(...) takes as its second argument a vector of numeric. But

 breaks<- classIntervals(tr1$unemployed, n=5, style='sd')

produces a list with two elements: 'var' and 'brks'. You need to use breaks$brks in findInterval(...).

Your statement

plot(tr1, col=colours[findInterval(tr1$unemployed, breaks, all.inside=T), axes=F])

attempts to plot tr1, which is not a map, it's a data frame with 402 rows. You need to plot(tracts,...)

Finally, why do you believe it is difficult to add layers in ggplot??