首页 > 解决方案 > 调查分类数据的分组条形图

问题描述

我的数据看起来像这样 在此处输入图像描述 在此处输入图像描述

   Q1[data$Q11 == -99] <- NA

Q1s<- factor(Q1 , labels = c("Strongly Disagree", "Disagree", "Neither Agree nor Disagree", "Agree", "Strongly Agree"))
levels(SQ1s )# how many levels of a categorical variable
Q11frequency <- table (Q1s ) #frequency
Q11frequency
#percentages
Q1_PERCENTAGE=prop.table(table(Q1s)) * 100
Q1_PERCENTAGE

barplot(Q1_PERCENTAGE)


Q2[data$Q2 == -99] <- NA

Q2s<- factor(Q2s , labels = c("Strongly Disagree", "Disagree", "Neither Agree nor Disagree", "Agree", "Strongly Agree"))
levels(Q2s )# how many levels of a categorical variable
Q2sfrequency <- table (Q2s ) #frequency
Q2sfrequency
#percentages
Q2s_PERCENTAGE=prop.table(table(Q2s)) * 100
Q2s_PERCENTAGE

barplot(Q2s_PERCENTAGE)

我得到单独的图表,例如在此处输入图像描述

但我正在寻找数据的组条形图。有什么帮助吗?

标签: rggplot2

解决方案


如果我理解正确,这可能会对您有所帮助

#Libraries

library(tidyverse)

#Example Data
qlevels <- c("Strongly Disagree", "Disagree", "Neither Agree nor Disagree", "Agree", "Strongly Agree")
         
df <- 
  tibble(
    Q1 = runif(n = 100,1,5),
    Q2 = runif(n = 100,1,5),
    Q3 = runif(n = 100,1,5),
    Q4 = runif(n = 100,1,5)
  ) %>% 
  mutate(
    across(.fns = round),
    across(.fns = function(x)factor(x,labels = qlevels))
    )

#How to

df %>% 
  #Pivot data to create a single column for all Q values
  pivot_longer(cols = everything()) %>% 
  #Count for each Question and level
  count(name,value) %>% 
  group_by(name) %>% 
  mutate(p = 100*n/sum(n)) %>% 
  ggplot(aes(x = name,y = p))+
  geom_col(aes(fill = value), col = "black")+
  scale_fill_brewer(type = "div")

在此处输入图像描述


推荐阅读