meri
meri

Reputation: 29

Change date format and keep chronological order in graph in R

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 :)

Upvotes: 0

Views: 726

Answers (1)

danlooo
danlooo

Reputation: 10637

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)

Upvotes: 0

Related Questions