4

I want to plot a shape file using ggplot2 in R. More specifically, I want to plot % white living in each block for several major cities. So far, I've worked with New Haven. The problem is that some blocks are unpopulated, in which case % white = NA. Ggplot automatically draws these blocks in grey. I would like to draw them in white.

New Haven with grey NAs

c_opts <- theme(axis.text.x=element_blank(), 
axis.text.y=element_blank(), 
axis.title.x=element_blank(), 
axis.title.y=element_blank(), 
axis.ticks = element_blank(),
legend.text=element_text(size=10), 
legend.background=element_blank(), 
legend.key=element_rect(fill='transparent', colour=NA), 
panel.grid.major=element_line(colour='white'), 
panel.background=element_rect(fill='transparent', colour=NA),
legend.justification=c(0,0), 
legend.position=c(.15,.15),
legend.title=element_text(size=11, face='bold'))

map <- qplot(PolyCoordsY, PolyCoordsX, data=nh_geom, group=Poly_Name, fill = pc_nhwhite, geom="polygon", xlab = "", ylab = "", main = "New Haven") 
map + c_opts + scale_fill_gradient(name = "% White")

I can exclude the NAs by adding na.value = NA to the scale_fill_gradient argument.

map <- qplot(PolyCoordsY, PolyCoordsX, data=nh_geom, group=Poly_Name, fill = pc_nhwhite, geom="polygon", xlab = "", ylab = "", main = "New Haven") 
map + c_opts + scale_fill_gradient(name = "% White", na.value = NA)

New Haven with excluded NAs

Although this draws the NA blocks in white, it also excludes the polygon borders of the these blocks. Does anyone know how to keep the polygon outlines?

1
  • Please provide a reproducible dataset. Also, consider using ggplot() instead of qplot() as it is better for handling involved plotting tasks. Dec 2, 2012 at 21:50

1 Answer 1

0

Without a reproducible dataset, I can't test if this will work for your specific case.

Try passing a color to na.value like so:

scale_fill_gradient(name = "% White",na.value="white")
1
  • Using ggplot() instead of qplot() turned out to be a very good idea. I was able to come up with a satisfactory solution by adding a geom_polygon() argument after ggplot that subsets for the NAs: ggplot(aes(PolyCoordsY, PolyCoordsX, group=Poly_Name, fill=pc_nhwhite), data=nh_geom, main = "New Haven") + geom_polygon() + c_opts + scale_fill_gradient(name = "% White", na.value = NA) + geom_polygon(aes(PolyCoordsY, PolyCoordsX, colour = NA), data = subset(nh_geom, is.na(pc_nhwhite)), fill = "white", alpha = 0.5, linetype = 1, col = "grey", cex = 0.25) Dec 3, 2012 at 21:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.