繁体   English   中英

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

[英]How to `table` all factors columns and ggplot geom_bar with facet_wrap?

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 

我们可以在ggplot中使用geom_bar(stat = "identity"...,来绘制条形图,如下所示:
在此处输入图像描述

如何使用 ggplot geom_bar 和facet_wrap一次性绘制colacolbcolc如下? 在此处输入图像描述

我们将列gather为“长”格式,然后执行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)

试试这个

  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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM