2016-01-25 75 views
2

我想使用R创建条件微图。基本上,我想在p_1,p_2,q_1,q_2下面的示例中为四个不同的变量创建一个构面(网格布局),并绘制每个状态图的颜色编码为1,蓝色为0,绿色为0。数据可视化:使用ggplot2和构面布局的地图

下面是示例代码。对于变量p_1,p_2,q_1,q_2中的每个变量,用于颜色编码的数据是“mydata”,0代表绿色,1代表吹气。我如何在使用ggplot中完成此操作。

library(ggplot2) 
library(maps) 
library(scales) # for function alpha() 
us.dat <- map_data("state") 

ggplot(us.dat, aes(x=long, y=lat, group=group)) + geom_polygon(fill="grey65", colour = alpha("white", 1/2), size = 0.2) + 
    theme_bw() + theme(legend.position = "none", text = element_blank(), line = element_blank()) + coord_map("polyconic") 

# create random data 

states <- unique(us.dat$region) 
p_1 <- sample(0:1,49,replace=T) 
p_2 <- sample(0:1,49,replace = T) 
q_1 <- sample(0:1,49,replace=T) 
q_2 <- sample(0:1,49,replace = T) 

mydata <- as.data.frame(t(rbind(states,p_1,p_2,q_1,q_2))) 

下面的图表布局是我想用一个常见的图例来完成的。 enter image description here

回答

3

您需要重新格式化数据,以便使用由密钥标识的变量进行长格式化。然后你需要将它与空间数据合并。然后使用facet_wrap(~ key)创建四个面板。

试试这个:

library(dplyr) 
library(tidyr) 
us.dat %>% 
    dplyr::left_join(
    mydata %>% 
     tidyr::gather(key, value, -states), 
    by = c("region" = "states") 
) %>% 
    ggplot(aes(x=long, y=lat)) + 
    geom_polygon(aes(group=group, fill = value), 
       colour = alpha("white", 1/2), 
       size = 0.2) + 
    theme_bw() + 
    theme(# legend.position = "none", 
     line = element_blank(), 
     axis.text = element_blank(), 
     axis.title = element_blank(), 
     strip.background = element_blank(), 
     panel.border = element_blank() 
     ) + 
    coord_map("polyconic") + 
    facet_wrap(~ key) 

我增加了一些主题元素让它看起来类似于你想要什么。 您将需要使用scale_fill_manual()来获得所需的颜色。

+1

用户询问一个常见的图例,将'legend.position =“none”'改为'legend.position =“top”'? – bouncyball

+0

对,我错过了那部分问题。使用'facet_wrap'只会生成一个图例。我编辑了答案来注释'legend.position'参数。 –

+0

非常感谢,正是我所期待的。当我使用你的代码片段加入表格时出现以下错误:{Warning message: In left_join_impl(x,y,by $ x,by $ y): 加入因子和字符向量,胁迫字符向量},不确定为什么,因为州和地区都是焦炭。从我所看到的情况来看,你已经加入了两张表格,创建一个长格式正确的?请告诉我。谢谢 – forecaster