【发布时间】:2017-10-21 16:59:31
【问题描述】:
library(tidyverse)
library(ggplot2)
我正在尝试创建下面的条形图,但在重组数据时遇到了问题。我在下面提供了一些示例数据,我创建的速度很快,所以结果可能很奇怪,但我对如何使用 tidyverse 工具来设置数据更感兴趣。
Q1_Sat<-c("Sat","Sat","Sat","Other","Other","Other","Other","Other")
Q1_VSat<-c("VSat","Other","Other","VSat","VSat","VSat","VSat","VSat")
Q1_M<-c("SatVSat","SatVSat","SatVSat","SatVSat","Other","Other","SatVSat","SatVSat")
Q2_Sat<-c("Sat","Other","Sat","Other","Sat","Sat","Other","Other")
Q2_VSat<-c("VSat","Other","VSat","Other","VSat","VSat","VSat","VSat")
Q2_M<-c("SatVSat","SatVSat","SatVSat","SatVSat","SatVSat","SatVSat","SatVSat","Other")
Q3_Sat<-c("Sat","Other","Sat","Other","Sat","Sat","Sat","Sat")
Q3_VSat<-c("VSat","Other","VSat","Other","Other","Other","Other","VSat")
Q3_M<-c ("SatVSat","SatVSat","SatVSat","Other","Other","Other","Other","Other")
Q4_Sat<-c("Sat","Other","Other","Other","Other","Other","Other","Other")
Q4_VSat<-c("VSat","VSat","VSat","VSat","VSat","VSat","VSat","VSat")
Q4_M<-c("SatVSat","Other","Other","Other","Other","Other","SatVSat","SatVSat")
Q20<-c("Nat","Internat","Nat","Nat","Internat","Internat","Nat","Nat")
Calc_Sat<-c("Sat","Sat","Sat","Other","Other","Other","Sat","Sat")
Calc_VSat<-c("Other","Other","VSat","VSat","VSat","VSat","Other","VSat")
PCode<-c("C11","C11","H12","F33","F33","C11","S33","F33")
CCode<-c("Dept","Camit","Camit","CCT","Dept","CCT","TTT","CCT")
Data<-data_frame(Q1_Sat,Q1_VSat,Q1_M,Q2_Sat,Q2_VSat,Q2_M,Q3_Sat,Q3_VSat,Q3_M,Q4_Sat,Q4_VSat,Q4_M,Q20,PCode,CCode,Calc_Sat,Calc_VSat)
下面是我到目前为止开发的代码,但我被困在这一点上,不知道如何为彩色分组条合并 Q20 变量。我想使用 Tidyverse 和 ggplot2 来实现这一点。任何其他关于如何使我的代码更加优雅和紧凑的反馈也将不胜感激。
Data%>%
select(-CCode,-Q1_M,-Q2_M,-Q3_M,-Q4_M)%>%
gather(key,value,-PCode,-Q20)%>%
filter(PCode=="C11")%>%
count(Q20,key,value)%>%
mutate(perc=round(n/sum(n),2))%>%
separate(key,c("Question","SatLevel"),sep="_")%>%
filter(value != "Other")%>%
ggplot(aes(x=Question,y=perc,fill=SatLevel))+geom_col()
【问题讨论】:
-
PCode和CCode未找到 -
抱歉,我添加了它们。希望您可以再试一次...
-
Rating未找到 -
Q20是什么?您的情节中是否需要它? -
你在这里问了五件事,其中大部分可以单独完成。试着每个问题问一件事,否则我们只是为你编写代码。