如何使用facet_wrap`表`所有因子列和ggplot geom_bar?

时间:2019-04-12 15:15:01

标签: r ggplot2

df <- data.frame(
    cola = c('1',NA,'c','1','1','e','1',NA,'c','d'),
    colb = c("a",NA,"c","d",'a','b','c','d','c','d'),
    colc = c('a',NA,'1','d','a',NA,'c',NA,'c','d'),stringsAsFactors = TRUE)

table(df$cola)

上述R脚本的输出为:

1 c d e 
4 2 1 1 

我们可以在geom_bar(stat = "identity"...,中使用ggplot来绘制如下图所示的条形图:
 enter image description here

如何将ggplot geom_bar与facet_wrap一起用于一次性绘制colacolbcolc,如下所示? enter image description here

2 个答案:

答案 0 :(得分:4)

我们将列gather设为'long'格式,然后执行ggplot

library(tidyverse)    
df %>%
     # gather to long format
     gather(na.rm = TRUE) %>%
     # get the frequency count of key, value columns
     count(key, value) %>% 
     ggplot(., aes(x = value, y = n)) + 
       geom_bar(stat = "identity") + 
       # facet wrap with key column
       facet_wrap(~ key)

答案 1 :(得分:3)

尝试一下

  library(tidyverse)

  df %>%
  map(function(x){as.data.frame(table(x))}) %>%
  bind_rows(.id = "variable") %>% 
  ggplot(aes(x = x, y = Freq)) +
  geom_col() +
  facet_wrap(~variable)