Create a percentage stacked bar chart

Hi nets,

welcome to the RStudio Community and your first topic! :slight_smile:
Below you will (may) find one possible solution for your posted problem, based on your minimal information. Try to use 'reprex' in future., it's a quite cool tool.

I've tried to restore your overall problem as good as possible with my reprex, but I'm not sure what your data looks like, especially for your labeling problem I may have misinterpreted your question... :wink:

library(tibble)
library(ggplot2)
library(tidyr)
library(dplyr)

#create some reprex data for testing of your output
set.seed(1234)
trend <- tibble('Q4 2017'=sample(c('< 25%','25 - 49.9%', '50 - 79.9%', '>= 80%'), 500, replace=TRUE),
                'Q1 2018'=sample(c('< 25%','25 - 49.9%', '50 - 79.9%', '>= 80%'), 500, replace=TRUE),
                'Q2 2018'=sample(c('< 25%','25 - 49.9%', '50 - 79.9%', '>= 80%'), 500, replace=TRUE),
                'Q3 2018'=sample(c('< 25%','25 - 49.9%', '50 - 79.9%', '>= 80%'), 500, replace=TRUE),
                'Q4 2018'=sample(c('< 25%','25 - 49.9%', '50 - 79.9%', '>= 80%'), 500, replace=TRUE)) %>% 
  gather(key='quarter', value='rating') %>% 
  #set your factor order
  mutate(quarter=factor(quarter, levels = c('Q4 2017','Q1 2018','Q2 2018','Q3 2018','Q4 2018'))) %>% 
  #set factors here in descending order to get the 'Lots' order you would like
  mutate(rating=factor(rating, levels = c('>= 80%','50 - 79.9%','25 - 49.9%','< 25%'))) %>% 
  group_by(quarter,rating) %>% 
  summarise('number'=n()) %>% 
  ungroup() %>% 
  #calculate the position (cumulative sums) for each column by hand and use later for ggplot
  arrange(quarter,desc(rating)) %>% 
  mutate('cumsums'=unlist(by(data = number, INDICES = quarter, FUN = cumsum)))

ggplot(data = trend, aes(y=number, x=quarter, fill=rating)) + 
  geom_bar(stat="identity", width = 0.5) + 
  xlab('') + ylab('Numbers of Lots') +
  #use 'cumsums' to set the 'value'-labels on the correct position for each bar
  #and adjusted position by hand '-10'...
  geom_text(aes(x = quarter, y = cumsums-10, label = number),
            colour = "white") + 
  labs(fill='Lots')

Created on 2019-03-15 by the reprex package (v0.2.1)

3 Likes