Search code examples
rplottime-series

X-axis of dates shifted to left in R barplot


I have an R data.frame with two columns. The var column contains any variable while the date column contains a daily sequence of dates. I'm trying to generate a barplot where the variable is plotted on the Y-axis and the dates on the X-axis.

Since there are too many dates, it would be convenient to add the 1st day of each month. I am doing the following:

# Example data
set.seed(1234)
df <- data.frame(
  var = runif(n=365, min=1, max=20),
  date = seq(from=as.Date('2021-01-01'), to=as.Date('2021-12-31'), by=1)
)

# Plot
barplot(df$var, 
        col="darkorange", border=NA, las=1, xaxt='n',
        main="var: random variable")
dts <- seq(from=as.Date(df$date[1]), to=as.Date(df$date[nrow(df)]), by="months")
ind <- c()
for(d in 1:length(dts)){
  m <- match(dts[d], df$date)
  ind <- c(ind, m)
}
axis(1, at=ind, labels=df$date[ind])
box()

enter image description here

However, the X-axis ticks are clearly shifted to the left. If you look at the last tick (representing "2021-12-01") it should appear almost at the end.

How can I solve this issue?


Solution

  • Update:

    According to this post How to put date on barplot() x-axis? using formula method is an easier option. We still have to consider the and tweak the width:

    Now there is no left shift!

    # Example data
    set.seed(1234)
    df <- data.frame(
      var = runif(n=365, min=1, max=20),
      date = seq(from=as.Date('2021-01-01'), to=as.Date('2021-12-31'), by=1)
    )
    
    # Plot
    
    barplot(df$var ~ df$date, col = "darkorange",
            border=NA, las=1, xaxt='n', width = 0.8,
            main="var: random variable", xlab = "date", ylab="var")
    
    dts <- seq(from=as.Date(df$date[1]), to=as.Date(df$date[nrow(df)]), by="months")
    ind <- c()
    for(d in 1:length(dts)){
      m <- match(dts[d], df$date)
      ind <- c(ind, m)
    }
    axis(1, at=ind, labels=df$date[ind])
    box()
    

    enter image description here