0

I'm trying to change my column "Week" to the date format %d/%m/%Y. I first convert the column type to date by doing mutate (Week = as.Date(Week)) and then I do mutate(Week = format(as.Date(Week), "d%/%m/%Y")) which does the job, however when I plot it as a graph I can't have the dates in chronological order because the column Week has become of type character.

Is there any way I can get my dates to be %d/%m/%Y and be plotted in chronological order?

Thanks :)

meri
  • 29
  • 2
  • don't convert week to a character. ggplot will work with the dates directly. Use scales_x_date(date_labels= ...) to fix the formatting – Richard Telford Sep 13 '21 at 16:33
  • thanks. I get my graph x ordered by day and month and not chronologically if I use this – meri Sep 14 '21 at 08:25

1 Answers1

0

Make sure that you parse the date character to a date object using your format. Then, ggplot recognizes this and puts the right labels to the x axis:

library(tidyverse)

data <-
  tibble(Date = c("30/11/2020", "01/12/2020")) %>%
  mutate(Date = Date %>% parse_date(format = "%d/%m/%Y"))
data
#> # A tibble: 2 x 1
#>   Date      
#>   <date>    
#> 1 2020-11-30
#> 2 2020-12-01

qplot(x = Date, y = 1, data = data)

Created on 2021-09-13 by the reprex package (v2.0.1)

danlooo
  • 10,067
  • 2
  • 8
  • 22
  • Thanks for your help. In the graph I get the format %B d% but I was looking for %d/%m/%Y? – meri Sep 14 '21 at 08:32
  • You can `qplot(x = Date, y = 1, data = data) + scale_x_date(date_labels = "%d/%m/%Y")` to adjust date format in the plot. The year was omitted because it is the same in all rows of my example. – danlooo Sep 14 '21 at 08:35
  • That finally worked! I added date_breaks so that all weeks were included and now it is in the correct format, thanks a lot, it is highly appreciated – meri Sep 22 '21 at 14:23