I am trying to plot waterfall chart using ggplot2. When I am placing the data labels it is not putting in the right place.
Below is the code I am using
dataset <- data.frame(TotalHeadcount = c(-417, -12, 276, -276, 787, 14), Category = LETTERS[1:6])
dataset$SortedCategory <- factor(dataset$`Category`, levels = dataset$`Category`)
dataset$id <- seq_along(dataset$TotalHeadcount)
dataset$type <- ifelse(dataset$TotalHeadcount > 0, "in", "out")
dataset[dataset$SortedCategory %in% c("A", "F"), "type"] <- "net"
dataset$type <- factor(dataset$type, levels = c("out", "in", "net"))
dataset$end <- cumsum(dataset$`TotalHeadcount`)
dataset$end <- c(head(dataset$end, -1), 0)
dataset$start <- c(0, head(dataset$end, -1))
dataset$value <-dataset$`TotalHeadcount`
library(ggplot2)
strwr <- function(str) gsub(" ", "\n", str)
ggplot(dataset, aes(fill = type))+ geom_rect(aes(x = SortedCategory, xmin = id - 0.45, xmax = id + 0.45, ymin = end, ymax = start))+ scale_x_discrete("", breaks = levels(dataset$SortedCategory), labels = strwr(levels(dataset$SortedCategory)))+ theme_bw()+ theme(panel.border = element_blank(), panel.grid.major = element_blank(), axis.line = element_line(colour = "gray"))+guides(fill=FALSE)
And below is the output. I want the data label to be just at the beginning or at the end of the bar. I am not very expert in R. Just trying to learn. Any help would be really appreciated.
I was following the below blog
https://learnr.wordpress.com/2010/05/10/ggplot2-waterfall-charts/
but somehow when I write the same code in geom_text it gives me an error. Could be a syntax related issue.