BuEX BuEX - 1 month ago 4x
R Question

R horizontal barplot with axis labels split between two axis

I have a horizontal barplot, with zero in the middle of the x-axis and would like the name for each bar to appear on the same side as the bar itself. The code I am using is:

cols <- c("blue", "red")[(abun > 0)+1]
barplot(abun, main="Predicted change in abundance", horiz=TRUE,
xlim=c(-0.04,0.08), col=cols, names.arg=species, las=1, cex.names=0.6)

I have tried creating two separate axes and the names do appear on the desired side for each bar, but are not level with the appropriate bar. I will try and upload an image of the barplot, am still very new to R, apologies if I am missing something basic!

barplot1- names in correct position but all on one axis

barplot2- names on both sides of plot but not in line with appropriate bar


We can accomplish this using mtext:

generate data

Since you didn't include your data in the question I generated my own dummy data set. If you post a dput of your data, we could adapt this solution to your data.

df1 <- data.frame(x = rnorm(20),
                   y = LETTERS[1:20])
df1$colour <- ifelse(df1$x < 0, 'blue', 'red')

make plot

bp <- barplot(df1$x, col = df1$colour, horiz = T)
mtext(side = ifelse(df1$x < 0, 2, 4),
      text = df1$y,
      las = 1,
      at = bp,
      line = 1)

enter image description here