Home > front end >  Percents on top of stacked bar graph R
Percents on top of stacked bar graph R

Time:03-15

I am trying to create a stacked bar graph in ggplot2 with percent shares on top of them. After looking at many other posts, I couldn't figure out a solution, so here are some sample data:

# load some libraries
library(ggplot2)

# make basic data frame
df <- data.frame(type = c("A", "A", "B", "B"),
                 year = c(2001,2002, 2001, 2002),
                 count_A = c(3, 2, NA, NA),
                 count_B = c(NA, NA, 8, 1),
                 sum_year_AB =  c(11,3,11,3),
                 total_count_with_irrelevant_types = c(13,14,19,23))

# create single percentage variable for top of bar
df$percent_AB_year = (df$sum_year_AB/df$total_count_with_irrelevant_types)*100
df$percent_AB_year = round(df$percent_AB, 1)
df$percent_final = paste0(df$percent_AB_year, "%")
df$percent_AB_year = ifelse(df$type=="B", NA, df$percent_AB_year)
df$percent_final = ifelse(df$type=="B", NA, df$percent_final)

enter image description here

Here is my code for the bar graph:

ggplot(df, aes(fill=type, x=year, y=sum_year_AB))   
  geom_bar(position="stack", stat="identity", width = .9)  
  labs(fill="Type",
       x = "Year",
       y = "Count",
       title = "Count by Year")  
  scale_x_continuous(breaks = seq(1999,2003,1))   
  geom_text(aes(label = percent_final), size = 3)  
  scale_fill_grey(start = .4, end = .6)

And here is the output of the graph: enter image description here

How do I put the percents on top?

CodePudding user response:

Use position = "stack" inside geom_text too:

ggplot(df, aes(fill=type, x=year, y=sum_year_AB))   
  geom_bar(position="stack", stat="identity", width = .9)  
  labs(fill="Type",
       x = "Year",
       y = "Count",
       title = "Count by Year")  
  scale_x_continuous(breaks = seq(1999,2003,1))   
  geom_text(aes(label = percent_final), size = 3, position = "stack", vjust = -0.2)  
  scale_fill_grey(start = .4, end = .6)

enter image description here

  • Related