ggplot2:使用位置==填充时向百分比堆积图添加标签?

Ahd*_*dee 1 r ggplot2

您好,当堆栈图标准化时,我似乎无法正确地将标签添加到堆栈图上。例如,

specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
data$value = round ( data$value, 2 )


# Stacked + percent
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="fill", stat="identity") 
Run Code Online (Sandbox Code Playgroud)

上面将产生一个标准化的堆栈图,但是当我添加

  geom_text(aes(label=value),
            position=position_stack(vjust=0.5))
Run Code Online (Sandbox Code Playgroud)

它不符合规范化。有办法解决这个问题吗?它类似于链接,但不完全是因为我不需要计算,而且我还添加了 stat="identity"

提前致谢。

ste*_*fan 5

当您用于position="fill"条形时,您也必须使用position=position_fill(vjust=0.5)ingeom_text来定位标签:

注意:我切换到geom_colgeom_bar(..., stat="identity")

set.seed(123)

library(ggplot2)

# Stacked + percent
ggplot(data, aes(fill = condition, y = value, x = specie)) +
  geom_col(position = "fill") +
  geom_text(aes(label = value),
    position = position_fill(vjust = 0.5)
  )
Run Code Online (Sandbox Code Playgroud)