我想我必须在这里忽略一些非常简单的事情。
我想将标签应用于一组多边形。具体来说,我正试图在少数加州国会选区上贴标签。
我首先获取底图(社交)并覆盖我的区SPDF(国会)的数据:
socal <- get_map(location = "Riverside, USA", zoom = 8, source = "google",
maptype = "roadmap")
somap <- ggmap(socal) +
geom_polygon(data = congress,
aes(x = long, y = lat, group = group),
fill = "#F17521", color = "#1F77B4", alpha = .6)
到现在为止还挺好。
但后来我想标记每个多边形,所以我创建了一个新变量:
congress@data$DistrictLabel <- paste("CD", congress@data$DISTRICT, sep = "")
当我尝试将其添加到我的地图时......
somap + geom_text(data = congress, aes(x = long, y = lat, label = DistrictLabel))
我收到以下错误:
eval中的错误(expr,envir,enclos):找不到对象'DistrictLabel'
我知道我忽略了一些明显的东西,但我无法弄清楚它是什么!任何帮助将非常感激。
谢谢!
对于标签,我通常首先导出多边形质心并根据这些来绘制。我不认为ggplot2有任何自动方式来定位基于多边形的文本标签。我想你必须指明它。像下面这样的东西应该工作:
library(dplyr)
library(sp)
library(rgeos)
library(ggplot2)
##Add centroid coordinates to your polygon dataset
your_SPDF@data <- cbind(your_SPDF@data,rgeos::gCentroid(your_SPDF,byid = T) %>% coordinates())
ggplot(your_SPDF) +
geom_polygon(data=your_SPDF,aes(x = long, y = lat, group = group),
fill = "#F17521", color = "#1F77B4", alpha = .6) +
geom_text(data = your_SPDF@data, aes(x = x, y = y),label = your_SPDF$your_label)