如何在 ggplot 中的堆叠条形图中放置标签,其中 y 轴是“计数”?

Edw*_*ese 0 label position r bar-chart ggplot2

绘制 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
Run Code Online (Sandbox Code Playgroud)

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

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!
Run Code Online (Sandbox Code Playgroud)

这就是我对 ggplot 的看法

(位置不对,需要交换位置并居中) 在此输入图像描述

J.C*_*Con 5

您可以position=position_stack(vjust=0.5)geom_text()通话中使用。

使用数据集的示例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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

根据如何计算百分比的请求进行编辑。

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述