ggplot,用浮动的彩色标记在美国的choropleth上标记东海岸的小州

ggplot,用浮动的彩色标记在美国的choropleth上标记东海岸的小州,r,ggplot2,maps,R,Ggplot2,Maps,我正在尝试创建一个美国choropleth,并希望为东海岸的小州添加标签,如本例所示: 我在地图上使用的代码是 gg <- ggplot() gg <- gg + geom_map(data = usfix, map = usfix, aes(x=long, y=lat, map_id=id), fill="#ffffff", color="#ffffff", size=0.15) gg <-

我正在尝试创建一个美国choropleth,并希望为东海岸的小州添加标签,如本例所示:

我在地图上使用的代码是

gg <- ggplot()
gg <- gg + geom_map(data = usfix, map = usfix, 
                    aes(x=long, y=lat, map_id=id), 
                    fill="#ffffff", color="#ffffff", size=0.15)
gg <- gg + geom_map(data = state.avg, map=usfix, 
                    aes(fill = score, map_id=id), 
                    color="#ffffff", size=0.15)
gg <- gg + labs(x=NULL, y=NULL)
gg <- gg + theme(panel.border = element_blank())
gg <- gg + theme(panel.background = element_blank())
gg <- gg + theme(axis.ticks = element_blank())
gg <- gg + theme(axis.text = element_blank())
gg <- gg + theme(panel.grid = element_blank())
gg <- gg + theme(legend.position = c(.15,.7))
gg <- gg + coord_fixed()
gg

gg根据hrbrmster的建议,我使用
ggplot\u build()
解决了这个问题,如下所示:

使用
str{utils}
ggplot\u build(gg)
对象中导航,我发现每个状态的颜色都在
ggplot\u build(gg)$data[[2]]$fill
中,状态标签在
ggplot\u build(gg)$data[[2]]$map\u id
中。因此,我可以使用

ggplot_build(gg)$data[[2]]$fill[which(ggplot_build(gg)$data[[2]]$map_id == 'utah')]
因此,我可以使用

state.getcolor <- function(x) {
  ggplot_build(gg)$data[[2]]$fill[which(ggplot_build(gg)$data[[2]]$map_id == x)]
}
eastcoast.colors <- sapply(c("massachusetts", "rhode island", "connecticut", "new jersey", 
                           "delaware", "maryland", "district of columbia"), state.getcolor)
我仍然不能完全确定它为什么会失败,并在data.frame中出现错误“error”(x=2500000,y=c)(1e+06,0,-1e+06,-2e+06,-3e+06,:
参数表示不同的行数:1、7、51“当我试图删除
geom_point
geom_text
中的数据规范时,我假设错误意味着在没有指定数据的情况下,它会尝试使用数据进行地图绘制,但我并没有要求它对数据做任何事情-只是绘制点。因此,我对ggplot的理解可能仍然存在差距。

你同意吗uld使用
ggplot\u build
获取颜色分配,然后在
geom\u point
调用中使用它们。此外,您还可以使用
rgeos::gCentroid
获取这些较小状态的状态质心,以用作x/y对,如果您确实想绘制一条线的话。谢谢,这太完美了!我将留下一个更详细的描述,我作为n为子孙后代回答这个问题-在这种情况下,这是正确的礼仪,对吗?是的。你将做艰苦的工作:-)
state.getcolor <- function(x) {
  ggplot_build(gg)$data[[2]]$fill[which(ggplot_build(gg)$data[[2]]$map_id == x)]
}
eastcoast.colors <- sapply(c("massachusetts", "rhode island", "connecticut", "new jersey", 
                           "delaware", "maryland", "district of columbia"), state.getcolor)
gg <- gg + geom_point(aes(x=2500000, y=(-1:5)*(-100000)), color = eastcoast.colors, 
                      data = state.avg[state.avg$STATE_CODE %in% 
                      c("MA", "RI", "CT", "NJ", "DE", "MD", "DC"),])
gg <- gg + geom_text(aes(label = c("MA", "RI", "CT", "NJ", "DE", "MD", "DC"), 
                     x=2600000, y=(-1:5)*(-100000)), hjust=0, size=3, 
                     data = state.avg[state.avg$STATE_CODE %in% 
                     c("MA", "RI", "CT", "NJ", "DE", "MD", "DC"),])