Добавление дат всех месяцев года по оси x ggplot2

#r #ggplot2 #tsibble

#r #ggplot2 #tsibble

Вопрос:

Есть ли способ показать все даты по оси x? У меня есть следующий набор данных, и мне нужен ggplot, в котором по оси x у меня есть year_month столбец, а по оси y — count столбец, НО я хотел, чтобы он показывал все месяцы в масштабе, а не только некоторые, как это обычно делает ggplot2.

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

Я пытался

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

Но успеха не достигнуто, так как он показывает только некоторые years months данные, записанные по оси x.

Ответ №1:

Вы можете использовать этот breaks аргумент, чтобы задать функцию, возвращающуюся каждый месяц. Поскольку ваши данные охватывают более 3 лет, это много перерывов…

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

введите описание изображения здесь