使用facet_wrap向堆积条形图添加计数和标签

Mac*_*iej 3 r ggplot2

我想用来ggplo2分析Likert规模变量.我想得到这种图形(下图),但我不知道如何在堆叠条上添加标签,并为每个分组变量和facet变量(for facet_wrap)插入不同的计数和均值.

我将不胜感激任何帮助!

数据可以从这里获得

我的代码:

library(ggplot2)
library(scales)
library(RColorBrewer)

ggplot(example,aes(GroupungVar,fill=VarOfInterest)) + geom_bar(position='fill') +      
scale_fill_manual(values = (brewer.pal(5, "Greens"))) + 
facet_wrap(~FacetVar,ncol=1) + coord_flip() + 
scale_y_continuous(labels=percent) + ylab('Percent')
Run Code Online (Sandbox Code Playgroud)

我得到了什么......

在此输入图像描述

..以及我想要实现的目标(数字与数据集中的数字不同).我希望每组标签中有计数(N),条形上的百分比标签和右侧的平均值(当然每组).百分比和平均值应该是图中所有条形的,我只将它们添加到前几个,只是为了表明我的意思.

在此输入图像描述

Mac*_*iej 8

我和R和ggplot2度过了一夜,我得到了我想要的东西:)

library('ggplot2')
library('plyr')
library('RColorBrewer')
library(scales)


label_positions<- function(x) {
  n<-length(x)
  wynik<-numeric(n)
  for (i in 1:n){
    if (i==1) {
      wynik[i]<-0+x[i]/2
    }
    else {
      wynik[i]<-x[i]-(x[i]-x[i-1])/2
    }
  }
  return(wynik)
}

exam1<-ddply(example,.(GroupingVar,FacetVar,VarOfInterest), 'nrow')
exam1.1<-ddply(example,.(GroupingVar,FacetVar),summarise, sr=mean(as.numeric(VarOfInterest),na.rm=T),
               odch=sd(as.numeric(VarOfInterest,na.rm=T)))

exam1<-merge(exam1,exam1.1,by.x=c('GroupingVar','FacetVar'),by.y=c('GroupingVar','FacetVar'))

names(exam1)[4]<-'Count'

exam2<-mutate(exam1,cumul=ave(Count,list(GroupingVar,FacetVar),FUN=cumsum),
              N=ave(cumul, list(GroupingVar,FacetVar),FUN=max),
              CumSumPercent=cumul/N*100,
              Freq=Count/N*100)


exam2<-mutate(exam2,cfrq = ave(CumSumPercent, list(GroupingVar,FacetVar), FUN = label_positions))
exam2$XLabel<-paste(exam2$GroupingVar,' (N=',exam2$N,')',sep='')
exam2$PosMean<-105

p<-ggplot(exam2, aes(x = Etykieta, y = Freq, fill = VarOfInterest)) +
  geom_bar(stat = 'identity',colour="black") +
  labs (x = "", y = "Percentage", fill=" ") + 
  scale_fill_brewer(name="Rating", palette="Greens", breaks = rev(levels(exam2$VarOfInterest))) +
  geom_text(aes(y = cfrq, label=paste(sprintf("%.01f",Freq), "%", sep='')), size=5) +
  geom_text(aes(y=PosMean,label=paste(sprintf("%.02f",sr),' (',sprintf("%.02f",odch),')',sep='')),size=5)+
                      facet_wrap(~FacetVar,ncol=1)  +
                       coord_flip() + ylab('Procent odpowiedzi') + 
  guides(fill=guide_legend(title=NULL)) + theme_bw()  + 
  theme(legend.position="bottom",strip.text.x=element_text(size=15,face='bold'),
        axis.text.x =element_text(size=12,face='bold'), axis.text.y =element_text(size=12,face='bold'),
        axis.title.x=element_text(size=15,face='bold'), axis.title.y=element_text(size=15,face='bold'),
        strip.background=element_rect(colour='black'))

plot(p)
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述