r - Annotation of summary statistic on ggplot above bars on barchart -


i created function takes dataframe, x , y variables , group variable arguments outputs barchart levels of x variable , facet group variable. want place text label above bar represents average of y. function worked until function follows:

   xtabar<- function(ds,xcat,yvar,group,formet=percent,color1=orange,color2=blue,...){     library(ggplot2)   library(dplyr)   library(scales)   localenv<-environment()   gg<-data.frame(ds,x=ds[,xcat],y=ds[,yvar],z=ds[,group] )   gg = transform(summarise(group_by(gg, x), sumvar= mean(y))) g<-ggplot(gg,aes(x=factor(x),y=y, fill=factor(x)))+stat_summary(fun.y=mean,geom="bar")+facet_wrap(~z)+scale_y_continuous(labels = formet)+xlab(xcat)+ylab(yvar)+scale_fill_manual(values=c(color1,color2)) #h<-g+geom_text(data=gg,aes(label=sumvar,x=factor(x),y=y), position = position_dodge(width = 0.8), vjust=-.6)  h<-g+stat_summary(fun.y = mean, geom="text", aes(label=sumvars), vjust = 0)  #g+scale_fill_manual(values=c("orange","blue"))+ylab("boo")+xlab("foo")+scale_y_continuous(labels = met) print(h)  }  # arguments dataframe (ds); x variable (xcat) y variable (yvar); grouping variable (group) y scale format (formet); , colors bars 

the error following:

error in layout_base(data, vars, drop = drop) :    @ least 1 layer must contain variables used facetting 

so can me code or understand logic can learn how summary stats above bar? thank you

an example 1 dataset:

# create dataset set.seed(123) df <- data.frame(xcol=sample(1:3, 100, replace=true), ycol = rnorm(100, 5, 2), catg=letters[1:5])  # summarising data require(plyr) df2 <- ddply(df, .(xcol, catg), summarise, ave=mean(ycol))  # creating plot ggplot(df2, aes(x=factor(xcol),y=ave, fill=factor(xcol))) +   geom_bar(stat="identity") +   geom_text(aes(label=round(ave,2)), vjust = -0.5) +   scale_y_continuous(limits=c(0,7), expand = c(0, 0)) +   guides(fill=false) +   facet_wrap(~catg) +   theme_bw() 

which results in: enter image description here


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -