Problems with changing the date scale on an axis

Hey guys,

I have the following data.frame

date     ratio
 1992-1    0.5
 1992-1    0.6
 1992-1    0.5
 1992-2    0.7
 1992-2    0.65
 1992-2    0.65

and I try to run the following code to create a graph

occratiocomb <- ggplot() +
  # blue plot
  geom_line(data=SKILL_1_OCC_FINAL, aes(x=Date, y=ratio_1occ_comb, group = 1, colour="very low")) + 
  geom_smooth(data=SKILL_1_OCC_FINAL, aes(x=Date, y=ratio_1occ_comb), method = loess, fill="red",
              colour="red", size=1) + theme(axis.text.x=element_text(angle=60, hjust=1))

occratiocomb + scale_x_date(date_breaks = "1 year", date_labels = "%Y")

The x axis (date) of my graph is looking terrible since I have monthly data as well as it shows a period of 30 years. The thing I try to do now is to change the date scale from a scale based on months to one based on years. Unfortunately, if I try to run the code the error date_trans works with objects of class Date only, is displayed. In my opinion, this is weird because my date column is already in a date format. Or is the issue related to the fact that my date variable does not contain any days?

Many thanks in advance

Yes, that is exactly why. scale_x_date() can only be used with date variables and you have a character variable instead, please see this example:


sample_df <- data.frame(
  stringsAsFactors = FALSE,
              date = c("1992-1","1992-1","1992-1",
             ratio = c(0.5, 0.6, 0.5, 0.7, 0.65, 0.65)

sample_df %>%
    mutate(date = as.Date(paste0(date, "-1"))) %>% 
    ggplot(aes(x = date, y = ratio)) +
    geom_line(aes(group = 1, colour="very low")) + 
    geom_smooth(method = loess, fill = "red", colour = "red", size = 1) +
    scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
    theme(axis.text.x = element_text(angle = 60, hjust = 1))

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

Note: Next time please provide a proper REPRoducible EXample (reprex) illustrating your issue.


Thanks for your help!
My problem was that it have not recognized my variable Date as a date variable.
The following code fixed it. sample_df$Date <- zoo::as.Date(zoo::as.yearmon(sample_df$Date))

Many thanks anyway

1 Like

This topic was automatically closed 21 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.