0

I need display the percentage value on the bars of a bar chart in R.

This code plots categorical data, with the categories on x and % on y. How to modify it such that it displays the percentage on the bars themselves, not just on the y-axis?

ggplot(data = iris) + 
  geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
  scale_y_continuous(labels = percent)
divibisan
  • 11,659
  • 11
  • 40
  • 58
Bayram Sarilmaz
  • 103
  • 1
  • 3
  • 13

2 Answers2

2

The ..count.. helpers in ggplot can be good for simple cases, but it's usually better to aggregate the data at the appropriate level first, not in your ggplot call:

library(tidyverse)
library(scales)

irisNew <- iris %>% group_by(Species) %>% 
 summarize(count = n()) %>%  # count records by species
 mutate(pct = count/sum(count))  # find percent of total

ggplot(irisNew, aes(Species, pct, fill = Species)) + 
  geom_bar(stat='identity') + 
  geom_text(aes(label=scales::percent(pct)), position = position_stack(vjust = .5))+
  scale_y_continuous(labels = scales::percent)

vjust = .5 centers the labels in each bar

Mako212
  • 6,787
  • 1
  • 18
  • 37
1
ggplot(data = iris, aes(x = factor(Species), fill = factor(Species))) +
geom_bar(aes(y = (..count..)/sum(..count..)),
         position = "dodge") + 
geom_text(aes(y = (..count..)/sum(..count..), 
              label = paste0(prop.table(..count..) * 100, '%')), 
          stat = 'count', 
          position = position_dodge(.9), 
          size = 3)+ 
labs(x = 'Species', y = 'Percent', fill = 'Species')
Shirin Yavari
  • 626
  • 4
  • 6