Search code examples
rggplot2geom-bar

R: show values in geom_bar(position = 'fill')


I have the following fake data:

n <- 100

set.seed(1)
df <- data.frame(grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
                 values = sample(1:10, n, replace = TRUE) )

df

My goal is to have a "filled" barplot as follow, but I don't know how to use geom_text() in order to add the values of the percentages for each segment of the bars.

ggplot(df, aes(x = values, fill = grp)) +
  geom_bar(position = 'fill') +
  geom_text(??)

Can anyone help me please?


Solution

  • Are you looking for something like this?

    df2 <- as.data.frame(apply(table(df), 2, function(x) x/sum(x)))
    df2$grp <- rownames(df2)
    df2 <- reshape2::melt(df2)
    
    ggplot(df2, aes(x = variable, y = value, fill = grp)) +
      geom_col(position = "fill") +
      geom_text(aes(label = ifelse(value == 0, "", scales::percent(value))),
                position = position_fill(vjust = 0.5)) +
      scale_y_continuous(labels = scales::percent, name = "Percent") +
      labs(x = "Value")
    

    enter image description here