2015-02-09 79 views
0

填寫多邊形考慮以下從ggmap小插曲使用ggmap

library(ggplot2) 
library(ggmap) 
library(rgeos) 
library(sp) 
library(maptools) 

# get an example shape file 
download.file('http://www2.census.gov/geo/tiger/PREVGENZ/tr/tr00shp/tr48_d00_shp.zip', destfile = 'census.zip') 

# unzip 
unzip("census.zip"); 

# read data into R 
shapefile <- readShapeSpatial("tr48_d00.shp", proj4string = CRS("+proj=longlat +datum=WGS84")) 

# convert to a data.frame for use with ggplot2/ggmap and plot 
data <- fortify(shapefile) 
qmap("texas", zoom = 6, maptype = "satellite") + geom_polygon(aes(x = long, y = lat, group = group), 
data = data, colour = "white", fill = "black", alpha = .4, size = .3) 

現在的問題例如:

我想用一個變量來填充多邊形,這樣的:

# define a vector for the fill aestetic 
fill_colour <- as.factor(1:length(shapefile)) 
# plot 
qmap("texas", zoom = 6, maptype = "satellite") 
    + geom_polygon(aes(x = long, y = lat, group = group, fill = fill_colour), data = data, alpha = .4,size = .3) 

但這不起作用,我得到以下錯誤:

Error: Aesthetics must either be length one, or the same length as the dataProblems:fill_color 
+0

我嘗試的鏈接。但似乎該zip文件不再可用。 – jazzurro 2015-02-09 15:41:27

+0

感謝您注意到這一點,我修復了鏈接並簡化了代碼 – Grigory 2015-02-09 19:06:17

回答

0

我找到了解決方案使用geom_map得到了類似的結果:

fill_colour <- as.factor(1:length(shapefile)) 
qmap("texas", zoom = 6, maptype = "satellite") + geom_map(inherit.aes = FALSE, aes(fill=fill_colour, map_id = 1:length(shapefile)), map=data) + scale_fill_manual(values = c("0" = "red", "1" = "blue"))