Set Axis Limits in ggplot2 Plot

I have this graphic with a dataframe that starts in mar18 and ends in fev21. Despite that, R wrote fev18 and mar21.

How can I adapt this code of this video to my problem?

scale_x_date(breaks = "1 month", date_labels = "%b %y")

Did you try the limits argument?

Edit:

I was wrong. For some reason, it's handled by expand argument, not limits.

set.seed(seed = 104653)

library(ggplot2)

df <- data.frame(
  date = seq.Date(
    from = as.Date(x = "2018-03-01"),
    to = as.Date(x = "2021-02-01"),
    by = "1 month"
  ),
  price = rnorm(n = 36)
)

ggplot(data = df) +
  geom_line(mapping = aes(
    x = date,
    y = price
  )) +
  scale_x_date(
    date_breaks = "1 month",
    date_labels = "%b %y",
    expand = c(0, 0)
  ) +
  theme(axis.text.x = element_text(angle = 90))

Session info ``` r sessionInfo() #> R version 4.0.3 (2020-10-10) #> Platform: x86_64-apple-darwin17.0 (64-bit) #> Running under: macOS Catalina 10.15.7 #> #> Matrix products: default #> BLAS: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib #> LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib #> #> locale: #> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 #> #> attached base packages: #> [1] stats graphics grDevices utils datasets methods base #> #> other attached packages: #> [1] ggplot2_3.3.3 #> #> loaded via a namespace (and not attached): #> [1] pillar_1.6.0 compiler_4.0.3 highr_0.9 R.methodsS3_1.8.1 #> [5] R.utils_2.10.1 tools_4.0.3 digest_0.6.27 evaluate_0.14 #> [9] lifecycle_1.0.0 tibble_3.1.1 gtable_0.3.0 R.cache_0.15.0 #> [13] pkgconfig_2.0.3 rlang_0.4.11 reprex_2.0.0 DBI_1.1.1 #> [17] curl_4.3.1 yaml_2.2.1 xfun_0.22 xml2_1.3.2 #> [21] httr_1.4.2 withr_2.4.2 styler_1.4.1 stringr_1.4.0 #> [25] dplyr_1.0.6 knitr_1.33 generics_0.1.0 fs_1.5.0 #> [29] vctrs_0.3.8 tidyselect_1.1.1 grid_4.0.3 glue_1.4.2 #> [33] R6_2.5.0 fansi_0.4.2 rmarkdown_2.8 farver_2.1.0 #> [37] purrr_0.3.4 magrittr_2.0.1 backports_1.2.1 scales_1.1.1 #> [41] ellipsis_0.3.2 htmltools_0.5.1.1 assertthat_0.2.1 mime_0.10 #> [45] colorspace_2.0-1 labeling_0.4.2 utf8_1.2.1 stringi_1.6.1 #> [49] munsell_0.5.0 crayon_1.4.1 R.oo_1.24.0 ```

Hope this helps.

1 Like

Thank you @Yarnabrina

It worked.

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