小编ekm*_*kmz的帖子

将组均值线添加到geom_bar图并包括在图例中

我希望能够创建一个条形图,该条形图还显示每个组中条形的平均值。AND显示图例中的平均值条。

我已经能够使用下面的代码来获得带有条形图的图表,这很好,但是我希望能够看到图例中的均线。

在此处输入图片说明

##The data to be graphed is the proportion of persons receiving a treatment
## (num=numerator) in each population (denom=demoninator). The population is 
##grouped by two age groups and (Age) and further divided by a categorical 
##variable V1

###SET UP DATAFRAME###
require(ggplot2)    
df <- data.frame(V1 = c(rep(c("S1","S2","S3","S4","S5"),2)), 
               Age= c(rep(70,5),rep(80,5)), 
               num=c(5280,6570,5307,4894,4119,3377,4244,2999,2971,2322),
               denom=c(9984,12600,9425,8206,7227,7290,8808,6386,6206,5227))

df$prop<-df$num/df$denom*100

PopMean<-sum(df$num)/sum(df$denom)*100

df70<-df[df$Age==70,]
group70mean<-sum(df70$num)/sum(df70$denom)*100

df80<-df[df$Age==80,]
group80mean<-sum(df80$num)/sum(df80$denom)*100

df$PopMean<-c(rep(PopMean,10))
df$groupmeans<-c(rep(group70mean,5),rep(group80mean,5))
Run Code Online (Sandbox Code Playgroud)

我希望该图看起来像这样,但也希望图例中的线条被标记为“组均值”或类似的值。

 #basic plot
 P<-ggplot(df, aes(x=factor(Age), y=prop, fill=factor(V1))) +
   geom_bar(position=position_dodge(), colour='black',stat="identity")    

 P
####add mean lines    
P+geom_errorbar(aes(y=df$groupmeans, ymax=df$groupmeans, 
ymin=df$groupmeans), col="red", lwd=2)
Run Code Online (Sandbox Code Playgroud)

添加show.legend …

r ggplot2 geom-bar

4
推荐指数
1
解决办法
1238
查看次数

标签 统计

geom-bar ×1

ggplot2 ×1

r ×1