0

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?

D. Studer
  • 1,711
  • 1
  • 16
  • 35
  • does this work for you? https://stackoverflow.com/questions/44724580/add-percentage-labels-to-a-stacked-barplot – StupidWolf Oct 29 '20 at 08:37

1 Answers1

1

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87