在ggplot中可视化一个因子与多个其他因子之间的关系

时间:2018-06-07 18:38:02

标签: r ggplot2

我有数据框

DF1 <- data.frame(V1 = factor(c("Yes", "No", "Yes", "No", "No")),
                 V2 = factor(c("Yes", "No", "No", "Yes", "No")),
                 V3 = factor(c("No", "Yes", "No", "No", "No")),
                 Location = factor(c("London", "Paris", "Dallas", "Dallas", "Dallas")))

如果我想想象Location和其他一个变量之间的关系,我可以画一个简单的情节:

library(ggplot2)    
ggplot(DF1, aes(Location)) + 
      geom_bar(aes(fill = V1), position = "dodge")

但是,如果我想在一个图中显示对所有其他变量(V1/2/3)的响应是按Location怎么办?有没有办法在ggplot中执行此操作?

1 个答案:

答案 0 :(得分:1)

您需要使用tidyr::gather转换为长格式,然后添加一个方面......

library(tidyr)

DF1 %>% gather(key=key,value=value,-Location) %>% 
ggplot(aes(Location,fill=value)) + 
  geom_bar(position = "dodge") + 
  facet_wrap(~key)

enter image description here