lukeg
lukeg

Reputation: 1357

Creating a stacked bar chart with counts printed in ggplot2

So i want to create a stacked bar chart, with frequency counts printed for each fill factor.

Showing data values on stacked bar chart in ggplot2

This question places the counts in the center of each segment, but the user specifies the values. In this example we dont input the specific value, and I am seeking an r function that automatically calcualtes counts.

Take the following data for example.

set.seed(123)
a <- sample(1:4, 50, replace = TRUE)
b <- sample(1:10, 50, replace = TRUE)
data <- data.frame(a,b)
data$c <- cut(data$b, breaks = c(0,3,6,10), right = TRUE,
                         labels = c ("M", "N", "O"))
head(data)

ggplot(data, aes(x = a, fill = c)) + geom_bar(position="fill")

So I want to print a "n= .." for M,N and O value in 1,2,3 and 4

So the end result looks like

enter image description here

Similiar to this question, however we do not have fr

Upvotes: 1

Views: 2175

Answers (1)

DatamineR
DatamineR

Reputation: 9618

Try the following:

obj <- ggplot_build(p)$data[[1]]

# some tricks for getting centered the y-positions:
library(dplyr)
y_cen <- obj[["y"]]
y_cen[is.na(y_cen)] <- 0
y_cen <- (y_cen - lag(y_cen))/2 + lag(y_cen)
y_cen[y_cen == 0 | y_cen == .5] <- NA

p + annotate("text", x = obj[["x"]], y = y_cen, label = paste("N = ", obj[["count"]]))

Which gives:

enter image description here

Upvotes: 1

Related Questions