Setting xmin and xmax with a yearmon date variable in ggplot2

I want to present a plot with a date variable formatted as year-mon (yearmon) in the x-axis.

I formatted the year-mon variable like this:

GP$time <- as.yearmon(paste(GP$year, GP$month, sep = "-"))
head(GP$time) # look at it
plot(suiciderate ~ time, GP) # plot it

Giving this formatting:

[1] "Jan 2012" "Feb 2012" "Mar 2012" "Apr 2012" "May 2012"

I have problems specifying xmin and xmax for the following plot:

GP_treatment <- ggplot(GP, 
                       aes(x = time, y = suiciderate, col = factor(intervention))) + 
  geom_smooth(se = FALSE) +
  annotate("rect", xmin = "Jan 2016", xmax = "Jul 2016", ymin = -Inf, ymax = +Inf, 
           alpha = .8) 

val = c("#E41A1C", "#377EB8")
lab = c("Control", "Treatment")  

GP_treatment +
  scale_x_continuous("Month", expand = c(0,0)) + 
  scale_y_continuous("Monthly suicide rate per 100 000", expand = c(0,0)) +
  scale_color_manual("Treatment status", 
                     values = val,
                     labels = lab)+

Running this just returns:

Error: Discrete value supplied to continuous scale

I suspect xmin and xmax must be specified otherwise, but I haven't found the solution yet. Hopefully someone can help me out on this.

That way you are passing a character string to a continuous scale (e. g. "Jan 2016"), I have never used zoo, but, maybe if you do this, it would work
xmin = as.yearmon("Jan 2016")

I would rather prefer to use a regular date variable and formatting the axis with scale_x_date()


Thanks! That solved the problem. I'm new to R, and the zoo package was the first thing I found looking for date formatting of month-year variables without dates in R. Could you point me to a source on regular formatting of such a date variable?

I was assuming that you already have a variable of class 'date' and that you can do something like this, but maybe that is not your case.

    data <- data.frame(
        time = as.Date(c("2018-01-06", "2018-02-06", "2018-03-06", "2018-04-06",
                         "2018-05-06", "2018-06-06")),
        ping = c(31.04, 30.09, 29.22, 29.33, 30.18, 27.8)
    data %>%
        ggplot(aes(time, ping)) +
        geom_line() +
        scale_x_date(date_breaks = 'months', date_labels = '%b-%Y')

Created on 2019-01-02 by the reprex package (v0.2.1)

You can read the documentation of scale_x_date() function by tiping this in the console

1 Like

Great, thank you for your helpful comments! I don't have such a variable, but I'll definitely look more into this.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.