0

This is the output I am aiming for where z will provide a plot of mine with an x-axis.

z<-c("2014-01", "", "", "2014-04", "", "", "2014-07", "", "","2014-10", "", "", "2015-01")

The plot will be produced once a month and I aim on automating the axis creation. 2015-01 is my last available data point and the plot will display a span of 1 year back to 2014-01. Next update will make me want to set the plot to 2015-02 to 2014-02.

As can be seen, the labelling of the axis goes back in 3 month steps, leaving the ticks in between empty.

Can I automate this process by providing just the latest label 2015-02 and the rest gets deducted by R somehow?

I was thinking maybe to convert my starting point 2015-01 to a date Format and sequence it back to 2014-01. Then making it a character again and using it for the axis...

myz <- as.Date(c("2014-01", "2015-01"), "%Y - %m")

But myz is empty. And ofc the problem with the empty tick is far froms olved.

Any advice?

alx.chrs
  • 127
  • 3
  • 15
  • 1
    You might want to look at `ggplot2` which has the `scale_x_date` parameter which takes the `date_breaks` argument. This argument can be set to "3 months" for example. – Haboryme Feb 02 '17 at 11:03
  • `as.Date` requires a day, so paste on one.. `rng <- as.Date(paste(c("2014-01", "2015-01"), "-01"), "%Y - %m -%d")` , you can the use `seq`, and `format` ... `format(seq(rng[1], rng[2], "3 months"), "%Y-%m")` – user20650 Feb 02 '17 at 11:08
  • @user20650 - This would work if not for the empty ticks in between the displayed date strings. Is there a way to define `format(seq(rng[1], rng[2], "3 months"), "%Y-%m")` as to display "", "", in between each date that is output? like `format(seq(rng[1], "", "" rng[2], "3 months"), "%Y-%m")` @Haboryme: ill look into it. not sure if i can transport my plot into ggplots syntax... – alx.chrs Feb 02 '17 at 13:22

1 Answers1

0

This might be done more efficiently but here is a solution:

version <- "201701"
endDate = as.Date(paste0(version,"01"), "%Y%m%d")

startDateString = paste0(as.integer(substr(version, 1, 4)) - 3, substr(version, 5, 6))
startDate = as.Date(paste0(startDateString,"01"), "%Y%m%d")

rngx <- format(seq(startDate, endDate, "3 months"), "%Y-%m")


output = c()
for(i in 1:(length(rngx)-1)) {
  output = c(output, rngx[i], "", "")
}
output = c(output, rngx[length(rngx)])

version <- "201701" marks the start date (and is used for some other parts in the script as well, for example the setwd()

alx.chrs
  • 127
  • 3
  • 15