如何在ggplot2中的geom_bar()上放置标签(没有手动y_position)

MBn*_*nnn 1 r ggplot2

我,这是我的问题.

我想用ggplot2创建一个geom_bar,条形图上有标签.

这是一个可重现的例子和生成的图:

prop = c(rep("A",2),rep("B",2),rep("C",2))
n = c(rep(29,2),rep(63,2),rep(25,2))
var = c(rep(c("sortant","entrant"),3))
value = c(10,19,43,20,10,15)
mydata = data.frame(cbind(prop,n,var,value))

> mydata
prop  n     var value
   A 29 sortant    10
   A 29 entrant    19
   B 63 sortant    43
   B 63 entrant    20
   C 25 sortant    10
   C 25 entrant    15

mydata$n = as.integer(as.character(mydata$n))
mydata$value = as.integer(as.character(mydata$value))

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我想制作这个情节,而不是手动创建"y_pos"(如下面的例子),因为我每周都要用不同的数据制作这个情节.

mydata2 = mydata
mydata2$y_pos = c(7,20,20,50,7,17)

>mydata2
prop  n     var value y_pos
   A 29 sortant    10     7
   A 29 entrant    19    20
   B 63 sortant    43    20
   B 63 entrant    20    50
   C 25 sortant    10     7
   C 25 entrant    15    17

ggplot(data = mydata2)+aes(x = prop, y = value, fill = var)+geom_bar(stat = 'identity')+
  scale_fill_brewer(palette = 'Paired')+geom_text(aes(label = value, y = y_pos))
Run Code Online (Sandbox Code Playgroud)

使用此代码,我有我想要的图,但我不想手动创建一些变量:

在此输入图像描述

如果有可能,我该如何制作这个图:

  • 价值很高

  • 按正确的顺序

  • 在正确的地方?

在此先感谢,任何帮助或例外都是值得的!

注意:(我不想使用position_dodge(),我想保留这种格式)

GGa*_*mba 5

您可以使用position参数里面geom_textposition_stack():

library(ggplot2)

ggplot(data = mydata)+aes(x = prop, y = value, fill = var)+
    geom_col()+
    scale_fill_brewer(palette = 'Paired')+
    geom_text(aes(label = value), position = position_stack(vjust = .5))
Run Code Online (Sandbox Code Playgroud)