Search code examples
rbar-chartoverlap

How to fix axis title overlapped with axis labels in barplot?


I have generated a bar plot/histogram for my data which shows the number of transactions for pack size. However, labels on x axis for the bars are out of the margin. The plot is presented below. enter image description here

I have tried to fix this by setting the outer margin to par(oma=c(3,3,0,0)). Here is my new plot. enter image description here

Although, the labels are inside the graph margin, but the x-axis title is still overlapped with the labels. How should I adjust the axis title so it is not overlapped with the labels?

Any suggestions would be very much appreciated!


Solution

  • Use axis and mtext.

    par(mar=c(11, 6, 4, 2))
    b <- barplot(data$v, ylim=c(0, 2e4), yaxt='n',
            main='Number of Transactions by Life Stage Histogram'
            )
    mtext(data$l, 1, .5, at=b, las=2, cex=.7)
    axis(2, labels=F)
    mtext(axTicks(2), 2, .75, at=axTicks(2), las=2)
    mtext('Life Stage', 1, 9)
    mtext('Freequency', 2, 4)
    

    enter image description here

    Or maybe that might be better:

    par(mar=c(3, 5, 4, 3))
    b <- barplot(data$v, ylim=c(0, 15e3), ylab='Frequency', yaxt='n',
                 main='Number of Transactions by Life Stage'
    )
    axis(2, labels=F)
    mtext(axTicks(2), 2, .75, at=axTicks(2), las=2, cex=.8)
    y <- (data$v) * c(1, 1, 1, 0, 0, 0, 0) + 500
    text(b, y, data$l, srt=90, adj=0, cex=.7)
    mtext('Life Stage', 1, 1)
    

    enter image description here


    Data:

    data <- structure(list(l = c("MIDAGE SINGLES/COUPLES", "NEW FAMILIES", 
    "OLDER FAMILIES", "OLDER SINGLES/COUPLES", "RETIREES", "YOUNG FAMILIES", 
    "YOUNG SINGLES/COUPLES"), v = c(7500, 2500, 1000, 15000, 15100, 
    10000, 15000)), class = "data.frame", row.names = c(NA, -7L))