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
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()
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?