具有组和构面的堆叠 ggplot 条形图的百分比标签

问题描述

我正在尝试将百分比标签添加到堆叠的多面条形图 (position='fill')。我希望每个条形显示的百分比相加。

我正在使用这样的数据集:

## recreate dataset
Village<-c(rep('Vil1',10),rep('Vil2',10))
livestock<-c('p','p','c','s','g','g')
dose<-c(3,2,1,3,4,1)
Freq<-c(4,5,6,8,1)
df<-data.frame(Village,livestock,dose,Freq)

我成功地绘制了它,并为每个 X 变量(牲畜)添加了加起来为 100% 的标签:

## create dose categories (factors)
df$dose<-as.character(df$dose)
df$dose[as.numeric(df$dose)>3]<-'>3'
df$dose<-factor(df$dose,levels=c('1','2','3','>3'))
## percentage barplot
ggplot(data = df,aes(x=livestock,y=Freq,fill=dose)) +
  geom_bar(position='fill',stat='identity') +
  labs(title="Given doses of different drugs in last 6months (livestock)",subtitle='n=89',x="Livestock",y="Percentage",fill = "Nr. of\ndoses") +
  theme(axis.text.x = element_text(angle = 45,hjust=1))+ 
  scale_y_continuous(labels=percent)+
  facet_wrap(~Village)+
  geom_text(aes(label = percent(..y../tapply(..y..,..x..,sum)[..x..])),stat = "identity",position = position_fill(vjust=0.5))

barplot 100% for each Xvariable

有谁知道我如何更改 ggplot 中的标签代码,以便每个条形的百分比加起来为 100%?也许与..group..有关?

我尝试了类似的方法:Label percentage in faceted filled barplot in ggplot2 put I can't make it work for my data.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)