rtextgraphcount

How do I add counts to a stacked bar graph?


Here is my graph so far:

counts <- table(all_study$study, all_study$time_of_day_num)
barplot(counts, main="Distribution of Enrollment Time by Study for 24-25",
        col=c("blue","red","green","yellow","orange"),
        ylab= "Count",  names.arg=c("Night", "Evening", "Day"))
legend(0.2,70, legend=c("MATIC","TCD-2","TROOP","Lublin","Microbiome"), 
       fill=c("orange","yellow","green","red","blue"), cex=0.75)

And here is what the graph looks like:

out

I am trying to figure out how to place the count of each study under each type of day. For example, it looks like there is about 25 Microbiomes under Night and 2 TROOP under Night. So I want the number 25 placed in the center of the blue bar for night and 2 squeezed into the green bar for night.

I have tried text() and things like stat='count' and more.


Solution

  • You could write an ymids() function, that calculates a cumulative sum, where the new element is always halved, i.e. x1/2, x1 + x2/2, x1 + x2 + x3/2, ... .

    > ymids <- \(x) {
    +   r <- numeric(length(x))
    +   for (i in seq_len(length(x))) {
    +     if (i == 1) {
    +       r[i] <- x[i]/2
    +     } else {
    +       r[i] <- sum(x[seq_len(i - 1)]) + x[i]/2
    +     }
    +   }
    +   r
    + }
    > b <- barplot(counts, col=hcl.colors(4, alpha=.5))
    > text(b, t(apply(counts, 2, ymids)), labels=t(counts))
    

    enter image description here

    If you really want these grey labels you can invent sth with rect, but IMO it would just clutter the plot and adds no useful information.


    Data:

    > dput(counts)
    structure(c(5L, 18L, 11L, 5L, 6L, 3L, 6L, 12L, 14L, 6L, 11L, 
    6L), dim = 4:3)