我想用ggplo2来分析李克特尺度变量。我想得到这样的图形(下图),但我不知道如何在堆叠的条形图上添加标签,并为每个分组变量和刻面变量(对于facet_wrap)插入不同的计数和均值。
如果有任何帮助,我将不胜感激!
数据可以从here获取
我的代码:
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')我得到的..。

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

发布于 2012-10-01 18:51:27
我和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)和结果

发布于 2012-10-01 06:01:50
对于样本大小,我可能只会将它们放在轴标签中,而不是放在图形本身上:
library(plyr)
example <- ddply(example,.(FacetVar,GroupungVar),
transform,
GroupingVar = paste(as.character(GroupungVar)," - (n=",length(GroupungVar),")",sep = ""))
ggplot(example,aes(GroupingVar,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')

https://stackoverflow.com/questions/12664820
复制相似问题