Search code examples
rdatebar-chartaxisaxis-labels

How to assign dates on x-axis to the barplot in R?


I have multiple dates data set that I would like to plot using barplot functions in R. The data is for two different periods so I want to have its respective dates on the x-axis for ease of comparison. Here is my code so far. A_Date is for dataset in A while B_Date is for dataset contain in B.

A= runif(24, min = 25, max = 45)
B=runif(24, min = 35, max = 100)
DF=rbind(A,B)

A_Date= as.data.frame(seq(as.Date("1987-01-01"), to= as.Date("1988-12-31"),by="months"))
names(A_Date)= "Dates"
A_Date$year=as.numeric(format(A_Date$Dates, "%Y"))
A_Date$month=as.numeric(format(A_Date$Dates, "%m"))
A_Date=A_Date[,-1]
A_Date = as.character(paste(month.abb[A_Date$month], A_Date$year, sep = "_" ))

B_Date= as.data.frame(seq(as.Date("2010-01-01"), to= as.Date("2011-12-31"),by="months"))
names(B_Date)= "Dates"
B_Date$year=as.numeric(format(B_Date$Dates, "%Y"))
B_Date$month=as.numeric(format(B_Date$Dates, "%m"))
B_Date=B_Date[,-1]
B_Date = as.character(paste(month.abb[B_Date$month], B_Date$year, sep = "_" ))

barplot(DF, beside = T, col = c("red","darkblue"), legend.text =c("1987-88", "2010-11"), args.legend =list(x="topleft", cex = 1.2, bty="n", x.intersp=0.2),
        ylab = "Precipitation (mm)", cex.axis = 1.2, cex.lab=1.5)

Also, I would like to have x-axis line (just like the line on y-axis. Thank you


Solution

  • barplot also throws a coordinate matrix, which we may catch by assignment, here by b <-. Now we can make an axis with ticks at the right places. To avoid that the plot becomes too crowded, we could unify the redundant month information and just split the different years in mtextlines. I've used here built-in month.abbs.

    b <- barplot(DF, beside=T, col=c("red","darkblue"), 
                 legend.text=c("1987-88", "2010-11"), 
                 args.legend=list(x="topleft", cex=1.2, bty="n", x.intersp=0.2),
                 ylab="Precipitation (mm)", cex.axis=1.2, cex.lab=1.5, ylim=c(0, 130))
    axis(1, at=b[1, ], labels=FALSE)
    axis(1, at=b[2, ], labels=FALSE)
    mtext(rep(c(1987, 1988), each=12), 1, 1, at=b[1, ], cex=.8, las=2)
    mtext(rep(c(2010, 2011), each=12), 1, 1, at=b[2, ], cex=.8, las=2)
    mtext(rep(month.abb, 2), 1, 3, at=colMeans(b), las=2)
    

     

    Result

    enter image description here

    If you'd also like to close the gap between y and x axis, you could add this line:

    abline(h=0, cex=1.3)