Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Percents on top of stacked bar graph R

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading