条形图上方 ggplot 上汇总统计的注释 [英] Annotation of summary statistic on ggplot above bars on barchart

查看:27
本文介绍了条形图上方 ggplot 上汇总统计的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数,该函数将数据帧、x 和 y 变量以及一个组变量作为参数,它按 x 变量的级别和组变量的分面输出条形图.我想在表示 y 平均值的条形上方放置一个文本标签.我的功能一直工作到我我的功能如下:

I created a function that takes dataframe, x and y variables and a group variable as arguments it outputs a barchart by levels of the x variable and facet by the group variable. I want to place a text label above the bar that represents the average of y. My function worked until I My function is as 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)

}

# The arguments are dataframe (DS); x variable (xcat) y variable (yvar); grouping variable (group) y scale format (formet); and colors for bars

我得到的错误如下:

Error in layout_base(data, vars, drop = drop) : 
  At least one layer must contain all variables used for facetting

那么任何人都可以帮助我编写代码或理解逻辑,以便我可以学习如何在栏上方获取汇总统计信息?谢谢

So can anyone help me with the code or understand the logic so that I can learn how to get summary stats above the bar? Thank you

推荐答案

一个只有一个数据集的例子:

An example with just one dataset:

# create a dataset
set.seed(123)
df <- data.frame(xcol=sample(1:3, 100, replace=TRUE), ycol = rnorm(100, 5, 2), catg=letters[1:5])

# summarising the data
require(plyr)
df2 <- ddply(df, .(xcol, catg), summarise, ave=mean(ycol))

# creating a 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()

导致:

这篇关于条形图上方 ggplot 上汇总统计的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆