我想制作一张地图,其中状态根据一个标准着色,并根据不同的标准进行交叉影线(或以某种方式以其他方式区分)。到目前为止我所拥有的是
library(ggmap)
library(mapdata)
library(ggplot2)
library(dplyr)
region<-c("california","nevada","oregon","washington")
var1<-c(0,1,0,1)
var2<-c(3,4,4,3)
my_data<-data.frame(region, var1, var2)
all_states_map <- map_data("state")
Total <- inner_join(all_states_map,my_data, by = "region")
Total$var1<-as.factor(Total$var1)
my_map <- ggplot() + geom_polygon(data=Total, aes(x=long, y=lat, group = Total$group, fill=Total$var1),colour="white",
show.legend=TRUE) + scale_fill_manual(values=c("blue","gray"))
所以现在我的状态是根据var1是0还是1来进行颜色编码。有没有办法在其上覆盖某些东西,以便在var2为3的交叉阴影状态,并且单独留下var2为4的状态?
答案 0 :(得分:2)
这是否与您希望看到的相近?
ggplot() + geom_polygon(data=Total, aes(x=long, y=lat, group = group,
fill = paste(var1, var2, sep = ", ")), colour="white") +
scale_fill_manual(values=c("blue","gray", "green", "red")) +
labs(fill = "(var1, var2)")
另一种选择是你将透明度设置为情节的另一个维度,所以它可能会更接近你想要的东西吗?
ggplot() + geom_polygon(data=Total, aes(x=long, y=lat, group = group,
fill = var1, alpha = as.factor(var2)), colour="white") +
scale_fill_manual(values=c("blue","red")) +
scale_alpha_manual(values = c(0.5, 1)) +
labs(alpha = "var2", fill = "var1")
答案 1 :(得分:1)
看起来在ggplot中没有简单的解决方案来解决这个问题。区分的一种方法是在折线周围使用不同的轮廓,如下例所示:
ggplot() +
geom_polygon(data=Total, aes(x=long, y=lat, group = Total$group,
fill=Total$var1,colour=as.factor(var2)),
,size=3,show.legend=TRUE) +
scale_fill_manual(values=c("blue","gray"))+
scale_color_manual(values=c("black",NA))
但是正如您所看到的,由于多边形绘图顺序,这会导致加利福尼亚州和其他州之间的线宽不一致。我们可以通过增加var2等于3的状态的组数来快速而肮脏地解决这个问题:
Total2<-Total%>%
mutate(group=ifelse(var2==3,group+100,group))
ggplot() +
geom_polygon(data=Total2, aes(x=long, y=lat, group = Total2$group,
fill=Total2$var1,colour=as.factor(Total2$var2)),
,size=3,show.legend=TRUE) +
scale_fill_manual(values=c("blue","gray"))+
scale_color_manual(values=c("black",NA))
如果你真的想要进行交叉影线,你可能不得不放弃ggplot这个:
答案 2 :(得分:1)
这可能不太理想但可能在某种程度上有所帮助?
library(ggmap)
library(mapdata)
library(ggplot2)
library(dplyr)
library(sp)
region<-c("california","nevada","oregon","washington")
var1<-c(0,1,0,1)
var2<-c(3,4,4,3)
my_data<-data.frame(region, var1, var2)
all_states_map <- map_data("state")
Total <- inner_join(all_states_map,my_data, by = "region")
Total$var1<-as.factor(Total$var1)
randomPoints <- NULL
# For each region find a set of points inside each state
for(i in region){
sub <- subset(Total, region == i)
sub.sr = SpatialPolygons(list(Polygons(list(Polygon(sub[,1:2])), "a")))
smple <- as.data.frame(spsample(sub.sr, n = 100, "regular"))
temp <- data.frame(x = smple[,1], y = smple[,2], region = i, var1 = unique(sub$var1), var2 = unique(sub$var2))
randomPoints <- rbind(randomPoints, temp)
}
ggplot() +
geom_polygon(data=Total, aes(x=long, y=lat, group = group, fill=var1), color = "white") +
geom_point(data = randomPoints, aes(x = x, y = y, shape = as.factor(var2)), size = 1) +
scale_shape_manual(values = c(1, 2))