I'm trying to create a barplot where each bar has an x-axis label "Name [linebreak] N=123", where the second line with "N=123" is displayed in a smaller font.
Consider this example:
t <- table(
factor(c(1, 1, 1, 1, 1, 1, 2, 1, 2, 2)),
factor(c(1, 1, 3, 2, 2, 2, 2, 2, 3, 1))
)
counts <- colSums(t) # 3, 5, 2
colnames(t) <- c("A", "B", "C")
barplot(t)
The figure looks like this (cropped):

I'd like to add the counts for each level A, B, C from the variable counts to the labels (in a smaller font), so that it looks something like this:

Is there any way to achieve that in R?
barplot returns "the coordinates of all the bar midpoints" (from ?barplot), which you can use to add text to the plot.
b <- barplot(t)
mtext(paste("N = ", counts), side=1, line=2, at=b)
# Use `mtext` to easily write to plot margins
# side=1 : bottom
# line=2 : counts out the way - so (I think) one is at the axis labels, so one more
# at: use the positions calculated by barplot
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With