根据每个类别R中的计数从多个数据框列创建条形图

时间:2018-08-03 15:20:01

标签: r ggplot2 bar-chart

我有以下data.frame示例:

df <- data.frame(c("a","c","d","e","e","a","a","b","b","a","d","a"),
                 c("b","b","d","e","e","a","a","b","b",NA,"d","e"),
                 c("c","c","d","c","e","b","a","d","d",NA,"c","e"),
                 c("d","d","b","e","e","a","a",NA,"b",NA,NA,"b"))
colnames(df) <- c("1st","2nd","3rd","4th")

我需要的是带有ggplot2的条形图,在这里我想根据数据帧中选定的列(不同颜色)显示答案的每个类别中的计数。按照excel的做法进行处理(尽管y上的频率与此data.frame不匹配)。还希望为NA设置类别或不带NA的显示选项。无法弄清楚。感谢您的宝贵时间。

ALSO-重要的是每次(对于每列)每个类别(a,b,c,d或e)将具有相同的颜色。

enter image description here

1 个答案:

答案 0 :(得分:3)

df <- data.frame(c("a","c","d","e","e","a","a","b","b","a","d","a"),
                 c("b","b","d","e","e","a","a","b","b",NA,"d","e"),
                 c("c","c","d","c","e","b","a","d","d",NA,"c","e"),
                 c("d","d","b","e","e","a","a",NA,"b",NA,NA,"b"))
colnames(df) <- c("1st","2nd","3rd","4th")

library(tidyverse)

df %>%
  gather() %>%                   # reshape date
  na.omit() %>%                  # exclude NAs
  ggplot(aes(key, fill=value))+  # plot
  geom_bar(position="dodge")

enter image description here