Adding all Year Month dates in a ggplot2 x-axis

1.1k views Asked by At

Is there a way to show all dates in the x-axis? I have the following dataset and I wanted a ggplot in which in the x-axis I've year_month column, and in the y-axis the count column, BUT I wanted it to show all months in the scale, not just some as the ggplot2 usually does.

    library(ggplot2)
    library(lubridate)
    library(tsibble)
    library(dplyr)
    
    plt = structure(list(month = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), year = c(2010, 
2012, 2012, 2012, 2013, 2013, 2014, 2014, 2014, 2014, 2014, 2014, 
2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 
2014, 2014, 2014, 2014, 2014, 2014, 2014), website = c("efarsas", 
"efarsas", "efarsas", "efarsas", "efarsas", "efarsas", "boatos_org", 
"boatos_org", "boatos_org", "boatos_org", "boatos_org", "boatos_org", 
"boatos_org", "boatos_org", "boatos_org", "boatos_org", "boatos_org", 
"boatos_org", "boatos_org", "boatos_org", "boatos_org", "boatos_org", 
"boatos_org", "boatos_org", "boatos_org", "boatos_org", "boatos_org", 
"boatos_org", "boatos_org", "boatos_org"), count = c(1L, 3L, 
3L, 3L, 2L, 2L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 
31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 31L, 
31L, 31L), year_month = structure(c(14610, 15340, 15340, 15340, 
15706, 15706, 16071, 16071, 16071, 16071, 16071, 16071, 16071, 
16071, 16071, 16071, 16071, 16071, 16071, 16071, 16071, 16071, 
16071, 16071, 16071, 16071, 16071, 16071, 16071, 16071), class = c("yearmonth", 
"vctrs_vctr"))), row.names = c(NA, -30L), groups = structure(list(
    month = c(1, 1, 1, 1), year = c(2010, 2012, 2013, 2014), 
    website = c("efarsas", "efarsas", "efarsas", "boatos_org"
    ), .rows = structure(list(1L, 2:4, 5:6, 7:30), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, 4L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

I tried

plt %>% 
  ggplot() +
  geom_line(aes(x = year_month, y= count, color = website)) +
  labs(color = "Fact-Checking Websites",
       x = "Month/Year (2010-2020)",
       y = "Quantity")+
   theme_minimal()

But no success achieved, as it only shows some years months written in the x-axis.

1

There are 1 answers

0
Gregor Thomas On BEST ANSWER

You can use the breaks argument to give a function returning each month. Since your data spans over 3 years, this is a lot of breaks...

plt %>% 
  ggplot() +
  geom_line(aes(x = year_month, y= count, color = website)) +
  labs(color = "Fact-Checking Websites",
       x = "Month/Year (2010-2020)",
       y = "Quantity")+
   theme_minimal() +
  scale_x_yearmonth(
    breaks = function(range) seq(range[1], range[2], by = 1),
    date_labels = "%m/%Y"
  )

enter image description here