r - 调查分类数据的分组条形图
问题描述
我的数据看起来像这样 在此处输入图像描述 在此处输入图像描述
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)
我得到单独的图表,例如在此处输入图像描述
但我正在寻找数据的组条形图。有什么帮助吗?
解决方案
如果我理解正确,这可能会对您有所帮助
#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")
推荐阅读
- string - 以pythonic方式获取字符串末尾的数字
- node.js - 可以在 CURL 中获取网站,但不能在 Nodejs 请求中获取
- python - OSError: [Errno 0] httplib2 请求中的错误
- php - Laravel 关系 - whereHas on hasMany
- javascript - 如何检测广告?
- python - Sublime Text 插件设置:未加载
- sql - SQL 触发器插入
- azure-active-directory - Azure Active Directory B2C 自定义错误页面被忽略
- javascript - 在 typedoc 中标记/生成方法链接?
- azure-devops - 防止 VSTS 中的后期构建事件