Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple lines and different font sizes in names.arg of a barplot in R?

Tags:

r

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):

Result

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:

Desired result

Is there any way to achieve that in R?

like image 328
Niko Avatar asked Dec 31 '25 08:12

Niko


1 Answers

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
like image 152
user20650 Avatar answered Jan 03 '26 04:01

user20650



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!