Home > Enterprise >  ggplot2: Adding a label to percent stacked plot when using position is == fill?
ggplot2: Adding a label to percent stacked plot when using position is == fill?

Time:04-22

Hi I can't seem to add labels to a stack plot correctly when it's normalized. For example,

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") 

The above will produce a normalized stack plot however when I add

  geom_text(aes(label=value),
            position=position_stack(vjust=0.5))

it does not conform to the normalization. Is there way around this? its similar to link but not quite since I don't need to calculate and I'm also adding in stat="identity"

thanks in advance.

CodePudding user response:

As you are using position="fill" for your bars you have to use position=position_fill(vjust=0.5) in geom_text too to position your labels:

Note: I switch to geom_col which is the same as geom_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)
  )

  • Related