Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks in advance.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading