rggplot2

How to show dates in a secondary x-axis while the primary x-axis is numerical?


Let's take this simple example:

ggplot(data.table(day = 1:3, value = c(2,3,1), date = Sys.Date() + 1:3), aes(x = day)) + 
  geom_line(aes(y = value)) + 
  scale_x_date(aes(x = date), position = "top")

It throws:

Error in transformation$transform(): ! transform_date() works with objects of class <Date> only

But the date column is of class <Date>, as str() shows.

I have also tried this way:

ggplot(data.table(day = 1:3, value = c(2,3,1), date = Sys.Date() + 1:3), aes(x = day)) + 
  geom_line(aes(y = value)) + 
  scale_x_continuous(sec.axis = sec_axis(~ as.Date(Sys.Date() + .), labels = date_format("%Y-%m-%d")))

This shows both scales, but it's not formatted as dates, but numbers. (date_format requires package scales).

How can I achieve to see the numeric x-axis on the bottom and the dates on top?


Solution

  • You can specify the breaks and labels for the secondary axis as follows:

    library(ggplot2)
    library(magrittr)
    
    data.frame(
      day = 1:3, 
      value = c(2,3,1), 
      date = Sys.Date() + 1:3) %>%  
    {ggplot(
      data = .,
      aes(x = day, y = value)
      ) + 
      geom_line() + 
      scale_x_continuous(
        # breaks = .$day,
        sec.axis = sec_axis(
          transform = ~ . * 1,
          breaks = .$day,
          labels = .$date)
      )}