2

I'm trying to plot a time serie with Primary x-axis as numeric and Secondary x-axis as date in ggplot. This is my poor try.

library(tidyverse)

tibble::tribble(
  ~date,  ~ndvi,
  "2020-05-18", 0.7655,
  "2020-06-14",  0.723,
  "2020-07-12", 0.6178,
  "2020-08-21",  0.437,
  "2020-09-07", 0.4763,
  "2020-09-10", 0.4928,
  "2020-09-12", 0.4831,
  "2020-09-22", 0.4774,
  "2020-10-02", 0.5794,
  "2020-10-07",  0.606
) %>% 
  mutate(date = lubridate::ymd(date),  
         weeks = difftime(date, min(date), units="weeks")) %>% 
  ggplot(aes(weeks, ndvi)) +
  geom_line()+
  scale_x_datetime(
    sec.axis = dup_axis(name = "", #breaks = date, 
                        labels = scales::time_format("%b")))

#> Error: Invalid input: time_trans works with objects of class POSIXct only

And this is the desired output, where the Primary x-axis has weeks and Secondary x-axis has the months of the time serie

enter image description here

tjebo
  • 21,977
  • 7
  • 58
  • 94
Juanchi
  • 1,147
  • 2
  • 18
  • 36
  • 1
    You haven't described your desired output. The image you included looks like the current output produced from your code. Can you be specific about what you wish to change? – Z.Lin Feb 10 '21 at 01:33
  • `scales::time_format("%^b")` seems a typo. `labels = scales::time_format("%b")` works as expected – Ronak Shah Feb 10 '21 at 02:33
  • Thanks @RonakShah but I don't think that is the problem with my code – Juanchi Feb 10 '21 at 09:37

1 Answers1

2

set labels for both x-axes separately. Please check also this discussion

library(tidyverse)

mydat <- tibble::tribble(
  ~date,  ~ndvi,
  "2020-05-18", 0.7655,
  "2020-06-14",  0.723,
  "2020-07-12", 0.6178,
  "2020-08-21",  0.437,
  "2020-09-07", 0.4763,
  "2020-09-10", 0.4928,
  "2020-09-12", 0.4831,
  "2020-09-22", 0.4774,
  "2020-10-02", 0.5794,
  "2020-10-07",  0.606
)  %>% 
  mutate(date = lubridate::ymd(date),  
         weeks = as.numeric(difftime(date, min(date), units="weeks")))

 mydat %>%
  ggplot(aes(date, ndvi)) +
  geom_line() +
  scale_x_date(date_breaks = "4 weeks", labels = scales::date_format("%W"),
    sec.axis = dup_axis(name = "", labels = scales::date_format("%b")))

Created on 2021-02-10 by the reprex package (v1.0.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • Thanks @tjebo, this is really helpful however I could probably was not very clear in my question since I would like to use new column `weeks` in x-axis – Juanchi Feb 10 '21 at 12:14