ggplot - Add percentage on top of bars

Problem

We want to add percent with the same number of decimals on top of a ggplot barchart.

data <- data.frame("patient"=c("A", "B", "C"), "value"=c(25, 20, 30))
ggplot(data, aes(x=patient, y=value)) + geom_col()
  patient value
1       A    25
2       B    20
3       C    30

Solution

Compute the percentage by adding a new column in the datafram. Use the function percent to chose the number of decimals and add a % sign Use geom_text to put the percent on top of the bar

data$pc <- percent(data$value/sum(data$value), 1)
ggplot(data, aes(x=patient, y=value)) + 
  geom_col() +
  geom_text(aes(label=pc))

Adjust the position of geom_text with vjust, we put -0.1 for a bit of padding, 0 would put exactly on the bar.

ggplot(data, aes(x=patient, y=value)) + 
  geom_col() +
  geom_text(aes(label=pc), vjust=-0.1)

How can we help?

Whether you already know about your data pain points or just want to have a friendly conversation, send us a message and tell us who you are.