Search code examples
rbar-chartxticks

R: Adjust spacing between ticks on barplot


I need to recreate a chart which was produced with R and edited with Inkscape afterwards. I'd like to do as much as possible in R. This is the chart:

enter image description here

Some of the text labels within the chart I will add later with Inkscape. My problem lies with the ticks. I decided to got for barplot() with no axes and add them separate with axis(). As you can see there is a spacing between the bars. I just don't know how to set a spacing for the ticks on the x-axis so that they are adjusted with the bars. Right now the ticks are getting off from the center. Here is my code:

mwe <- data.frame(month=c("Dec 2007", "Jan 2008", "Feb 2008", "Mar 2008","Apr 2008","May 2008","Jun 2008"),
                 job_difference_in_thousands=c(70, -10, -50, -33, -149, -231, -193),
                 color=c("darkred","darkred","darkred","darkred","darkred","darkred","darkred"))
                 
barplot(height=mwe$job_difference_in_thousands,
        axes=F,
        col=mwe$color,
        border = NA,
        space=0.1,
        main="Grafik X_1 NEW JOBS IN THE UNITED STATES",
        cex.main=0.75,
        ylim=c(-800,600),
)
axis(1,pos=0, lwd.tick=0, labels=F,line=1, outer=TRUE)
axis(1,at=0:6+0.5,labels=FALSE,lwd=0,lwd.tick=1)
axis(1, at=0:6+0.5,
     labels=mwe$month,
     cex.axis=0.65,
     lwd=0)
axis(2, at=seq(-800,600,by=200),las=2,cex.axis=0.65, lwd=0, lwd.tick=1)

Created on 2020-12-28 by the reprex package (v0.3.0)


Solution

  • R gives you back the positions of the bar midpoints when you call barplot. Therefore, simply storing the return of barplot and using this as the tick positions centers them.

    mwe <- data.frame(month=c("Dec 2007", "Jan 2008", "Feb 2008", "Mar 2008","Apr 2008","May 2008","Jun 2008"),
                     job_difference_in_thousands=c(70, -10, -50, -33, -149, -231, -193),
                     color=c("darkred","darkred","darkred","darkred","darkred","darkred","darkred"))
                     
    bar_pos <- barplot(height=mwe$job_difference_in_thousands,
            axes=F,
            col=mwe$color,
            border = NA,
            space=0.1,
            main="Grafik X_1 NEW JOBS IN THE UNITED STATES",
            cex.main=0.75,
            ylim=c(-800,600),
    )
    axis(1,pos=0, lwd.tick=0, labels=F,line=1, outer=TRUE)
    axis(1,at=bar_pos,labels=FALSE,lwd=0,lwd.tick=1)
    axis(1, at=bar_pos,
         labels=mwe$month,
         cex.axis=0.65,
         lwd=0)
    axis(2, at=seq(-800,600,by=200),las=2,cex.axis=0.65, lwd=0, lwd.tick=1)