简体   繁体   English

使用ggmap填充多边形

[英]Fill Polygons using ggmap

Consider following example from the ggmap vignette 考虑下面来自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)

Now the question: 现在的问题是:

I want to use a variable for filling the polygons, like this: 我想使用一个变量来填充多边形,像这样:

# 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)

But this doesnt work, I get following error: 但这不起作用,出现以下错误:

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

I found a solution using geom_map yielding a similar result: 我发现使用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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM