如何在 ggplot 的堆叠条形图中放置标签,其中 y 轴为 "count"?

How to position your labels in stacked bar graph plot in ggplot where the y axis is "count"?

绘制 ggplot,x 轴作为名称(分类),y 轴默认为计数

gnew = ggplot(data= got, aes(x= got$attacker_king, fill= got$attacker_outcome))+
    geom_bar() +
    geom_text(stat = "count", aes(label =..count..), vjust = -.5)+
    scale_y_continuous(limits = c(0,20)) # plotting the stacked ggplot #this works

尝试根据填充的位置定位标签

got = ddply(got, .(got$attacker_king), 
    transform, pos = cumsum(..count..)- (0.5 *..count..)) # positioning labels shows error

#This shows error as "Error in eval(expr, envir, enclos) : object '..count..' not found"

Please help!

这就是我的 ggplot

(位置不对,需要调换位置居中)

您可以在 geom_text() 调用中使用 position=position_stack(vjust=0.5)

使用 iris 数据集的示例。

library(ggplot2)

ggplot(data= iris, aes(x= Sepal.Width, fill= Species))+
  geom_bar() +
  geom_text(stat = "count", aes(label =..count..), position=position_stack(vjust=0.5))+
  scale_y_continuous(limits = c(0,20))

编辑 根据如何计算百分比的要求。

library(ggplot2)
library(dplyr)

summary<-as.data.frame(iris %>%
group_by(Species,Sepal.Width) %>%
  tally  %>%
  group_by(Sepal.Width) %>%
  mutate(pct=(100*n)/sum(n)))


ggplot(data= summary, aes(x= Sepal.Width, y=n,fill= Species))+
  geom_bar(stat='identity') +
  geom_text(aes(label =round(pct,2)), position=position_stack(vjust=0.5),size=3)+
  scale_y_continuous(limits = c(0,20))