Using ggplot to create a choropleth from a SpatialPolygonsDataFrame

你。 提交于 2020-01-13 18:54:19

问题


I have a SpatialPolygonsDataFrame that comes from the UScensus2010 package. I am trying to create a choropleth. When I do so, this works as expected:

data(colorado.county10)
choropleth(colorado.county10,
           "P0010001",
           color = list(fun = "rainbow", 
                        attr = list(4)),
           main="2010 US Counties",
           type="plot",
           border="black")

but this fails due to 'P0010001' not being found

data(colorado.county10)
ggplot(colorado.county10, aes(long, lat, group = group)) +
  geom_polygon(aes(fill = P0010001), colour = alpha("white", 1/2), size = 0.2) +
  scale_fill_brewer(pal = "PuRd")

As I've tried to figure this out, I've noted that colorado.county10$P0010001 returns an array of numbers, but colorado.county10[,"P0010001"] returns a SpatialPolygonsDataFrame.

Any insights into what is happening?


回答1:


If you want to use ggplot you need to coerce from a SpatialPolygonsDataFrame to a data.frame.

ggplot2 provides a number of fortify methods that will create the correctly formatted data.

Currently the fortify.SpatialPolygonsDataFrame method does not retain the data component, it does provide a column id which contains the rownames from the data.frame within the data slot of the original SpatialPolygonsDataFrame.

Note that data.frames are an inefficient way to store this information (1 row for each vertex for each polygon).

Thus the following will work, but is slow and may cause memory issues

c10 <- fortify(colorado.county10)

c10d <- cbind(c10, colorado.county10@data[c10$id,])

ggplot(c10d, aes(long, lat, group = group)) +
   geom_polygon(aes(fill = factor(P0010001)), colour = alpha("white", 1/2), size = 0.2) +
   scale_fill_brewer(pal = "PuRd") 

Using base plotting functions will be much faster and not chew up as many resources.



来源:https://stackoverflow.com/questions/20039297/using-ggplot-to-create-a-choropleth-from-a-spatialpolygonsdataframe

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