美国地图上的颜色特定状态[重复]

问题描述 投票:0回答:3

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

我正在使用这个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")

有关如何确保只有这些状态在地图上以相关颜色突出显示的任何想法?

r ggplot2
3个回答
1
投票

类似于James Thomas Durant的答案,但更多地反映了数据集的原始结构并减少了所需的短语:

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

enter image description here

我是StackOverflow的新手,所以不确定这些编辑是否应该是对原始答案做出的,但我觉得这些修改足够大,可以单独使用。请说我错了:)


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

enter image description here


1
投票
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") 

然后用另一种颜色重复“否定”。

© www.soinside.com 2019 - 2024. All rights reserved.