Problem with dates in x-axis

Hi, I have this df:

head(df)
# A tibble: 74.055 × 2
   year_fm per_fm     
     <dbl> <chr>      
 1    2015 prepandemia
 2    2015 prepandemia
 3    2015 prepandemia
 4    2015 prepandemia
 5    2015 prepandemia
 6    2015 prepandemia
 7    2015 prepandemia
 8    2015 prepandemia
 9    2015 prepandemia
10    2015 prepandemia
# ℹ 74.045 more rows

And I made this plot

df %>%
  ggplot(aes(x= year_fm, 
             fill= per_fm)) +
  geom_bar()

and I want to add dates to the x-axis and I tried with this line of code but I get this error

df %>%
  ggplot(aes(x= year_fm, 
             fill= per_fm)) +
  geom_bar() +
  scale_x_date(breaks = c(seq(ymd('2015-01-01'), 
                              ymd('2023-01-01'), 
                              by = '6 months')),
               date_labels = "%m-%Y")

Error: Invalid input: date_trans works with objects of class Date only

How can I solve it?

The x values are not dates, they are numbers that represent year values. Dates have the value of the number of days since 1970-01-01.
You can change the labels on the x axis using the labels argument of scale_x_continuous, as in the following example.

library(ggplot2)
DF <- data.frame(Year = c(2015,2015,2015,2016,2016,2017,2017,2017,2017),
                 Type = c("A","A","A","B","B","C","C","C","C"))
DF |> ggplot(aes(x = Year, fill = Type)) + geom_bar()

DF |> ggplot(aes(x = Year, fill = Type)) + geom_bar() +
  scale_x_continuous(breaks = 2015:2017, labels = c("2015-Jan", "2016-Jan", "2017-Jan"))

Created on 2024-04-12 with reprex v2.0.2

Your column with years is a numeric data type: there is a specific dateTime / Date data type / class for dates. This is why you get the error that it wants a Date class: when you use the layer scale_x_date() in the ggplot, it also wants the input for the x-axis to be "proper" Date data type.

You can change a column to proper dates this with the package lubridate. But then the question is: your dataframe only has years, but you want 6-monthly intervals on the x-axis?

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.