美国地图上的颜色特定状态[复制](Colour specific states on a US ma

2019-10-31 05:34发布

这个问题已经在这里有一个答案:

  • ggplot美国国家地图; 颜色有细,多边形锯齿- R的 2个回答

我用这GGPLOT2代码创建一个美国地图:

library(ggplot2)
all_states <- map_data("state")  
p <- ggplot()
p <- p + geom_polygon( data=all_states, aes(x=long, y=lat, group = group),colour="white", fill="grey30" )

现在我有一组我想画的红色和一对夫妇我要画绿色的状态。 像这样:

states_positive <- c("New York")
states_negative <- c("Texas")

我如何能确保只有这些国家在相关的颜色突出显示在地图上有什么想法?\

Answer 1:

类似的答案, 詹姆斯·托马斯杜兰特 ,但反映集多一点的原有的结构和较少的切割所需的短语:

library(ggplot2)
library(dplyr)

all_states <- map_data("state") 
# Add more states to the lists if you want
states_positive  <-c("new york")
states_negative  <- c("texas")

在ggplot,如果您进行子集相同的数据集,可以设置在第一ggplot()参数的美学,他们将被用于小区内的所有图层。

# Plot results
ggplot(all_states, aes(x=long, y=lat, group = group)) +
  geom_polygon(fill="grey", colour = "white") +
  geom_polygon(fill="green", data = filter(all_states, region %in% states_positive)) +
  geom_polygon(fill="red", data = filter(all_states, region %in% states_negative))

我是新来的StackOverflow所以不知道是否这些编辑应该已经到了原来的答案做出,但我觉得改变是足够实质性自己去放。 请说我错了:)



Answer 2:

你也可以手动添加多边形:

library(ggplot2)
library(dplyr)
all_states <- map_data("state")  
p <- ggplot()
p <- p + geom_polygon( data=all_states, aes(x=long, y=lat, group = group),colour="white", fill="grey30" )


ny <- filter(all_states, region == "new york")
tx <- filter(all_states, region == "texas")


p + geom_polygon(data = ny, aes(x=long, y=lat, group = group),fill="red") +
  geom_polygon(data = tx, aes(x=long, y=lat, group = group),fill="blue")



Answer 3:

library(ggplot2)
library(raster)

all_states <- map_data("state")  

data <- data.frame(Row.Labels=all_states$region,
                   LATITUDE=all_states$lat,
                   LONGITUDE=all_states$long)

data$positive <- ifelse(data$Row.Labels=="new york", "Yes", "No")

usa <- getData('GADM', country="US", level=1) 
f_usa <- fortify(usa)
i <- sapply(usa@data$NAME_1, function(x) agrep(x, data$Row.Labels, max.distance=.3, ignore.case=T)[1]) 
usa@data$positive <- data$positive[i]
f_usa <- merge(x=f_usa, y=unique(usa@data), by.x="id", by.y="ID_1",all.x=T) 
f_usa <- f_usa[with(f_usa, order(id, order)), ] 
f_usa$positive[is.na(f_usa$positive)] <- "No"
ggplot(f_usa, aes(x=long, y=lat, group=group, fill=positive)) + 
  geom_polygon(colour="black") 

然后用另一种颜色为“负面”重复。



文章来源: Colour specific states on a US map [duplicate]
标签: r ggplot2