【问题标题】:Data visualization: Maps using ggplot2 and facet layout数据可视化:使用 ggplot2 和 facet 布局的地图
【发布时间】:2016-05-02 08:54:55
【问题描述】:

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

以下是示例代码。用于颜色编码的数据是“mydata”,0 代表绿色,1 代表每个变量 p_1,p_2,q_1,q_2

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

下面的图表布局是我想用一个常见的图例完成的。

【问题讨论】:

    标签: r ggplot2 maps data-visualization facet


    【解决方案1】:

    您需要重新格式化您的数据,使其成为长格式,您的变量由一个键标识。然后你需要将它与空间数据合并。然后使用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() 来获得您想要的颜色。

    【讨论】:

    • 用户要求一个常见的图例,将legend.position = "none"更改为legend.position = "top"?
    • 对,我错过了问题的那一部分。 facet_wrap 只产生一个图例。我编辑了答案以注释掉 legend.position 参数。
    • 非常感谢,正是我想要的。当我使用您的 sn-p 加入表时出现以下错误,{警告消息:在 left_join_impl(x, y, by$x, by$y) 中:加入因子和字符向量,强制转换为字符向量},不确定为什么,因为州和地区都是字符。从我所见,您已经加入了两个表,以创建正确的长格式?请告诉我。谢谢
    • 使用gather() 完成转换为“长”格式。加入空间数据是必要的,因为您想要在 ggplot 中绘制的任何内容都需要位于单个数据框中。你看到的不是错误,而是警告。这是因为us.dat$region 是字符,mydata$states 是因素。另一种方法是创建没有因素的数据框。 dplyr 的 data_frame() 函数默认执行此操作。例如。 mydata &lt;- dplyr::data_frame(states, p_1, p_2, q_1, q_2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多