Limits for x-axis

Hi, I have the following script to create epicurve of COVID-19 cases from 2020 to 2023. However, the x-axis includes tick for months of 2024 onwards. I would like to limit it to 2023 only. I have tried including “limits = c(‘2020’, ‘2021’, ‘2022’, ‘2023’)” inside the “scale_x_date” but it results to error.

ggplot(NAT_weeklycases) +
  
  geom_area(
    aes(x = date_week, y = cases), fill  = "palegreen3") +
  
 geom_text(data = av7_maxdate, 
   aes(label = av7, x = date_week, y = cases),   #4th text
   hjust = .6, vjust = -2, size = 2.5) +
  
  geom_text(data = av7_maxdate, 
  aes(label = "7-day average (Week 48):", x = date_week, y = cases), #3rd text
    hjust = .6, vjust = -4, size = 2.5) +
  
  geom_text(data = cases_maxweek, 
   aes(label = "Cases (Week 48):", x = date_week, y = cases), #1st text
hjust = .6, vjust = -9, size = 2.5) +
  
  geom_text(data = cases_maxweek, 
           aes(label = cases, x = date_week, y = cases), #2nd text
            hjust = .6, vjust = -7, size = 2.5) +
  
 
  geom_line(
     aes(
       x = NAT_weeklycases$date_week, 
       y = average_7day, colour = "7-day average"), size = 0.6) +

  theme_minimal()+
  scale_color_manual(values = c("darkgreen")) +
  xlab("Month (Year)") +  
  ylab("No.of reported COVID-19 cases") +  
  scale_x_date(date_breaks = "1 month", 
               labels = function (x){
                 month_labels <- format(x, "%b")
                 year_labels <-  ifelse(format(x, "%m") == "01", format(x, "%Y"), "")
                 paste(month_labels, "\n", year_labels)
               }) +
  theme(axis.text=element_text(size = 8),
        axis.text.x = element_text(vjust = 0.5, hjust=0.5), 
        axis.title= element_text(size = 8)) +
  guides(color = guide_legend(title = NULL))

I hope you can help me.
Thank you.

Regards,
Echo

Hello @Echo_Bajador

Here’s how you can use the limits function inside scale_x_date:

scale_x_date(
 
  limits = c(start_date, end_date),
  
)
  • start_date: The minimum date you want to display on the x-axis.
  • end_date: The maximum date you want to display on the x-axis.

For example, if you want to limit the x-axis to the range from January 1, 2020, to December 31, 2023, you can use:

scale_x_date(
  limits = as.Date(c("2020-01-01", "2023-12-31")),
)

I can’t test the solution because you didn’t provide a sample of your dataframe so it’s not a reproducible example, but test it out and let me know if it works.

Lucca

Oh sorry the solution didn’t work, maybe because of the function I used inside the scale_x_date or the date_breaks?

Here is the snippet of my dataframe:

dput(head(NAT_weeklycases))

structure(list(date_week = structure(c(18288, 18295, 18302, 18309, 
18316, 18323), class = "Date"), week_report = c(4, 5, 6, 7, 8, 
9), year_report = c(2020, 2020, 2020, 2020, 2020, 2020), cases = c(1L, 
2L, 0L, 0L, 0L, 7L), n = c(4L, 7L, 7L, 7L, 7L, 7L)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
    date_week = structure(c(18288, 18295, 18302, 18309, 18316, 
    18323), class = "Date"), week_report = c(4, 5, 6, 7, 8, 9
    ), .rows = structure(list(1L, 2L, 3L, 4L, 5L, 6L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))
#>    date_week week_report year_report cases n
#> 1 2020-01-27           4        2020     1 4
#> 2 2020-02-03           5        2020     2 7
#> 3 2020-02-10           6        2020     0 7
#> 4 2020-02-17           7        2020     0 7
#> 5 2020-02-24           8        2020     0 7
#> 6 2020-03-02           9        2020     7 7

Thank you very much.

2 Likes

Hello,

I would use the expand argument to alleviate this, as seen below:

# Loading packages
library(tidyverse)
library(padr)

# Creating fake data
fake_data <-
    tibble(date = seq.Date(
        from = ymd("2020-01-01"),
        to = today(),
        by = "day"
    )) |>
    rowwise() |>
    mutate(n = rpois(n = 1, lambda = 10)) |>
    ungroup() |>
    thicken("week") |>
    group_by(date_week) |>
    summarize(n = sum(n)) |>
    mutate(year = year(date_week),
                 week = week(date_week))

# Plotting the fake data
ggplot(fake_data) +
    geom_segment(aes(
        x = date_week,
        xend = date_week,
        y = 0,
        yend = n
    )) +
    scale_x_date(date_breaks = "years", date_labels = "%Y", expand = c(0, 0)) +
    scale_y_continuous(breaks = scales::extended_breaks(),
                                         labels = scales::comma_format()) +
    coord_cartesian(xlim = c(as.Date("2020-01-01"), as.Date("2023-12-31"))) +
    labs(x = "\nWeek", y = "Number\n") +
    theme_minimal()

Created on 2023-12-16 with reprex v2.0.2

Session info
sessionInfo()
#> R version 4.3.1 (2023-06-16)
#> Platform: x86_64-apple-darwin20 (64-bit)
#> Running under: macOS Ventura 13.6.1
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRblas.0.dylib 
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.11.0
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> time zone: America/Toronto
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#>  [1] padr_0.6.2      lubridate_1.9.3 forcats_1.0.0   stringr_1.5.1  
#>  [5] dplyr_1.1.4     purrr_1.0.2     readr_2.1.4     tidyr_1.3.0    
#>  [9] tibble_3.2.1    ggplot2_3.4.4   tidyverse_2.0.0
#> 
#> loaded via a namespace (and not attached):
#>  [1] styler_1.10.2     utf8_1.2.4        generics_0.1.3    xml2_1.3.6       
#>  [5] stringi_1.8.2     hms_1.1.3         digest_0.6.33     magrittr_2.0.3   
#>  [9] evaluate_0.23     grid_4.3.1        timechange_0.2.0  fastmap_1.1.1    
#> [13] R.oo_1.25.0       R.cache_0.16.0    R.utils_2.12.3    fansi_1.0.6      
#> [17] scales_1.3.0      cli_3.6.2         rlang_1.1.2       R.methodsS3_1.8.2
#> [21] munsell_0.5.0     reprex_2.0.2      withr_2.5.2       yaml_2.3.7       
#> [25] tools_4.3.1       tzdb_0.4.0        colorspace_2.1-0  curl_5.2.0       
#> [29] vctrs_0.6.5       R6_2.5.1          lifecycle_1.0.4   fs_1.6.3         
#> [33] pkgconfig_2.0.3   pillar_1.9.0      gtable_0.3.4      glue_1.6.2       
#> [37] Rcpp_1.0.11       xfun_0.41         tidyselect_1.2.0  highr_0.10       
#> [41] rstudioapi_0.15.0 knitr_1.45        farver_2.1.1      htmltools_0.5.7  
#> [45] rmarkdown_2.25    labeling_0.4.3    compiler_4.3.1

All the best,

Tim

2 Likes

Thank you so much, it worked.
I have also tried the following to have “week-year” format and ta-da.

  scale_x_date(date_breaks = "weeks", 
               labels = function (x){
                 week_labels <- format(x, "%W")
                 year_labels <-  ifelse(format(x, "%W") == "01", format(x, "%Y"), "")
                 paste(year_labels, "Week-", week_labels) 
               },
               expand = c(0, 0))
1 Like