Skip to content

Version1.2 #123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 193 commits into from
Jun 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
193 commits
Select commit Hold shift + click to select a range
1ed79ef
svgfix initial changes
sarahcmap Nov 24, 2020
d9ababc
import svglite
sarahcmap Nov 25, 2020
4b80dad
import svglite
sarahcmap Dec 3, 2020
677cdaf
Merge branch 'master' into svgfix
sarahcmap Dec 3, 2020
3d53a48
Fixes bug, allows for current recessions
Mar 17, 2021
4720b83
Addresses Matt's comments
Mar 18, 2021
654736a
Shift date numeric calculation into function
Mar 18, 2021
23a02cd
Clarify recessions table
Mar 18, 2021
cc908ab
`update_recessions()` tweaks
matthewstern Mar 19, 2021
e72736f
tweak update_recessoins()
matthewstern Mar 19, 2021
7c376fe
shift `show_ongoing` work into `filter_recessions` subfn
matthewstern Mar 19, 2021
ac28c4d
address open issues
matthewstern Mar 19, 2021
dd326f7
rm unnecessary space in file
matthewstern Mar 19, 2021
ee111c3
Merge pull request #122 from CMAP-REPOS/geom_recessions_bugfix
matthewstern Mar 22, 2021
0639606
Replace deprecated arguments
Mar 23, 2021
ae4e11e
Add explanation of ongoing recessions
Mar 23, 2021
97bb7ef
Update man file
Mar 23, 2021
bc7a428
Rewording section on recessions
Mar 23, 2021
9323c7e
Update to documentation
Mar 23, 2021
1f2f08f
Initial code
Mar 23, 2021
1a3f270
Delete integer_breaks
Mar 23, 2021
bcc025a
Delete integer breaks
Mar 23, 2021
e1bba87
Revert "Delete integer_breaks"
Mar 23, 2021
1eb6360
Revert "Revert "Delete integer_breaks""
Mar 23, 2021
643903c
Improvements and date case
dlcomeaux Mar 24, 2021
f9fadda
Add date scale examples
dlcomeaux Mar 24, 2021
02328ea
Merge pull request #125 from CMAP-REPOS/vignettes_and_mans
matthewstern Mar 29, 2021
48952dd
Implements function factory
dlcomeaux Apr 1, 2021
8b4a879
Consolidates functions
dlcomeaux Apr 1, 2021
09aef14
resolve conflict
sarahcmap Apr 2, 2021
1c1a488
some improved functionality
matthewstern Apr 2, 2021
2637972
clean up
matthewstern Apr 2, 2021
008c459
one more thing
matthewstern Apr 2, 2021
904f541
- add ragg to imports
sarahcmap Apr 3, 2021
ee90666
set up env and font registry
matthewstern Apr 3, 2021
972f828
tweak
matthewstern Apr 3, 2021
12e15cb
revert back to `globals`
matthewstern Apr 3, 2021
7060aa5
implement envir getter and setter
matthewstern Apr 3, 2021
874bff3
documentation
matthewstern Apr 3, 2021
0f7bb58
left some notes
matthewstern Apr 3, 2021
1de5255
more fiddling
matthewstern Apr 3, 2021
02c1021
working now, check passes
matthewstern Apr 3, 2021
21d0bec
working get and set
matthewstern Apr 3, 2021
af920ef
mas
matthewstern Apr 3, 2021
b906067
documentation
matthewstern Apr 3, 2021
680c7ca
final changes? I hope
matthewstern Apr 5, 2021
9ca3cd9
set global tweak
matthewstern Apr 5, 2021
44fa37b
Update DESCRIPTION
matthewstern Apr 5, 2021
d8d99d7
Move helper functions into utilities.R
nmpeterson Apr 5, 2021
9169794
Minor edits
nmpeterson Apr 5, 2021
f87e295
Moved geoms_that_change definition into cmapplot_globals.R
nmpeterson Apr 5, 2021
6289616
Fixed typo
nmpeterson Apr 5, 2021
eed0806
Added note about font size units
nmpeterson Apr 5, 2021
3f345bf
Rebuilt documentation
nmpeterson Apr 5, 2021
65a0481
finalize changes applied to systemfonts branch
sarahcmap Apr 5, 2021
93b21af
- add comma to description
sarahcmap Apr 5, 2021
b2db618
Minor tweak to comment
Apr 5, 2021
07ac35e
Merge pull request #126 from CMAP-REPOS/x_axis_control
dlcomeaux Apr 5, 2021
cc4ca16
Merge branch 'version1.2' into systemfonts
matthewstern Apr 5, 2021
c4dcaa1
Corrected font size note
nmpeterson Apr 5, 2021
b721dee
Merge branch 'systemfonts' of https://github.com/CMAP-REPOS/cmapplot …
nmpeterson Apr 5, 2021
44fbb83
Create test pkgdown action
nmpeterson Apr 5, 2021
1b200fc
Rebuilt NAMESPACE
nmpeterson Apr 5, 2021
9db07e9
Reference list tweaks
nmpeterson Apr 5, 2021
11db673
Print all located font files in log
nmpeterson Apr 5, 2021
4da37df
Don't force all non-numeric types to character
nmpeterson Apr 5, 2021
cc40816
Attempt to register fonts
nmpeterson Apr 5, 2021
c3d3aa6
Corrected syntax issue
nmpeterson Apr 5, 2021
715fd28
Corrected another syntax issue
nmpeterson Apr 5, 2021
5a46945
Unload/reload cmapplot before deploy
nmpeterson Apr 5, 2021
130c5b2
Try devtools::reload() instead
nmpeterson Apr 5, 2021
fdcf783
One last attempt for the day...
nmpeterson Apr 5, 2021
32cb822
Just kidding, this is the real last attempt today
nmpeterson Apr 5, 2021
9ec7364
Check for Whitney in systemfonts::registry_fonts() too
nmpeterson Apr 6, 2021
2cfec6f
Manually register fonts
nmpeterson Apr 6, 2021
608be33
Print registry_fonts() family/path to log
nmpeterson Apr 6, 2021
c022a2b
a test
matthewstern Apr 6, 2021
11dc0ff
test 2
matthewstern Apr 6, 2021
f69c275
typo
matthewstern Apr 7, 2021
881a496
no italics?
matthewstern Apr 7, 2021
ac2932d
Register fonts from cloned repo instead of ~/Library/Fonts
nmpeterson Apr 7, 2021
a078643
typo fix
dlcomeaux Apr 8, 2021
f4e8d1b
print font registry in vignette
matthewstern Apr 10, 2021
418944f
print contents of VM font folder
matthewstern Apr 11, 2021
4b9e647
clean up pkgdown GHA
matthewstern Apr 11, 2021
da5ab92
typo
matthewstern Apr 11, 2021
3b08605
tweak font dir
matthewstern Apr 11, 2021
524f73a
another typo
matthewstern Apr 11, 2021
a8ba100
mac font registration attempt 1
matthewstern Apr 11, 2021
ad921ba
typo
matthewstern Apr 11, 2021
a20eb26
new branch
matthewstern Apr 12, 2021
1b519ac
test
matthewstern Apr 16, 2021
013787b
typo
matthewstern Apr 16, 2021
51b8f24
getting things working again
matthewstern Apr 19, 2021
b62472b
clean up vignette testing
matthewstern Apr 19, 2021
6c3e4ac
update pkgdown GHAs
matthewstern Apr 19, 2021
8274a64
Merge branch 'version1.2' into systemfonts
matthewstern Apr 19, 2021
90803ab
adjust location of preferred font names
matthewstern Apr 19, 2021
5ff89ba
Minor tweaks
nmpeterson Apr 21, 2021
bc4adb2
custom registration
matthewstern Apr 23, 2021
233773a
test message
matthewstern Apr 23, 2021
5ba8cde
new check
matthewstern Apr 23, 2021
cface8d
new check
matthewstern Apr 23, 2021
c76adff
new check
matthewstern Apr 23, 2021
ba44649
more checkssss
matthewstern Apr 23, 2021
5546ff2
new checks
matthewstern Apr 23, 2021
ba1590a
I think I found it!
matthewstern Apr 23, 2021
64e2ce8
lets try this
matthewstern Apr 23, 2021
0fe7e7f
famous last words
matthewstern Apr 23, 2021
c698e0f
whoops
matthewstern Apr 23, 2021
c56726b
check() works
matthewstern Apr 25, 2021
50a921d
require agg for rstudio graphics
matthewstern Apr 25, 2021
9daa57c
typo in grep
matthewstern Apr 25, 2021
53c8627
documentation updates
matthewstern Apr 25, 2021
8ce6f93
clearer messages
matthewstern Apr 25, 2021
6e6ea4e
simplify `try()` and clarify comments
matthewstern May 1, 2021
661667a
typo
matthewstern May 1, 2021
840b1d5
small tweaks
matthewstern May 2, 2021
c2c7b49
attempt at dynamic GHA workflow
May 2, 2021
e74c216
tweaks to GHA
May 2, 2021
8204056
Remove pkgtown test workflow, update main workflow
May 2, 2021
699f2da
Modified text formatting example
nmpeterson May 3, 2021
a1caf11
Modified text formatting example
nmpeterson May 3, 2021
612c01e
Handle edge case
dlcomeaux May 4, 2021
51d467e
add path length requirement
matthewstern May 4, 2021
bbdef8e
Merge pull request #128 from CMAP-REPOS/systemfonts
matthewstern May 4, 2021
a4d6e03
Merge branch 'version1.2' of https://github.com/CMAP-REPOS/cmapplot i…
sarahcmap May 4, 2021
ebdbb66
Update to reflect new font behavior
dlcomeaux May 6, 2021
b07fc89
Doesn't work, playing with it
dlcomeaux May 6, 2021
2cac68b
remove "window" mode
matthewstern May 7, 2021
c43da29
optimize device selection
matthewstern May 9, 2021
dc1869f
remove ref to window mode from vignette
matthewstern May 10, 2021
64f4ded
Revert "Doesn't work, playing with it"
dlcomeaux May 11, 2021
48a3bac
Add gradients to list of palettes
dlcomeaux May 11, 2021
fe9c20c
Update documentation
dlcomeaux May 11, 2021
8f3fee6
Update vignettes
dlcomeaux May 11, 2021
97f9efa
Colour/color tweak
dlcomeaux May 12, 2021
5d7e2d7
Change back to colour
dlcomeaux May 13, 2021
9852752
Update margin image references
dlcomeaux May 13, 2021
b5d485d
that didn't work
dlcomeaux May 13, 2021
5f376e1
Merge pull request #132 from CMAP-REPOS/vignette_image_fix
dlcomeaux May 27, 2021
ee2983c
Change case of file extensions
nmpeterson May 28, 2021
be9dd4b
Merge pull request #133 from CMAP-REPOS/vignette_image_fix
nmpeterson Jun 1, 2021
0c3353b
Merge pull request #131 from CMAP-REPOS/discrete_colors
gritzenthaler Jun 2, 2021
d2cfb08
Update vignette
dlcomeaux Jun 2, 2021
3d0a693
Test exports of SVGs with fonts
dlcomeaux Jun 2, 2021
89ffcff
Revert to svg
dlcomeaux Jun 3, 2021
9907002
Update documentation
dlcomeaux Jun 3, 2021
78308f6
Remove test exports
dlcomeaux Jun 3, 2021
a74775b
Remove svglite
dlcomeaux Jun 3, 2021
51b72d9
Update documentation
dlcomeaux Jun 3, 2021
7bf4562
Merge pull request #130 from CMAP-REPOS/v1.2finalizewfonts
dlcomeaux Jun 3, 2021
f01fd96
Add `abbr_years` to vignette
dlcomeaux Jun 4, 2021
7de2666
Update version number
nmpeterson Jun 9, 2021
657b849
Add RStudio prompt for vanilla R users
nmpeterson Jun 9, 2021
a0ae4bc
Minor grammar correction
Jun 9, 2021
efc60c5
Doc tweaks, smoother images from viz_gradient()
nmpeterson Jun 9, 2021
7dcf9f4
Merge branch 'version1.2' of https://github.com/CMAP-REPOS/cmapplot i…
nmpeterson Jun 9, 2021
d21e201
Reknit README with ragg
nmpeterson Jun 9, 2021
5986699
capitalization, line breaks, date
Jun 9, 2021
334848e
Change references to cmapplot_globals
Jun 9, 2021
cb5eaa7
Merge branch 'version1.2' of https://github.com/CMAP-REPOS/cmapplot i…
Jun 9, 2021
1f53e98
Grammar & clarity
nmpeterson Jun 9, 2021
187d4f4
Merge branch 'version1.2' of https://github.com/CMAP-REPOS/cmapplot i…
nmpeterson Jun 9, 2021
0bba6ba
Code formatting, minor clarification
nmpeterson Jun 9, 2021
18c667c
Minor tweaks
nmpeterson Jun 9, 2021
2f71be2
Display CMAP logo on pkgdown site
nmpeterson Jun 10, 2021
03fc0bf
Update DESCRIPTION
nmpeterson Jun 10, 2021
de46419
remove bmp mention
sarahcmap Jun 11, 2021
0561d73
updated news.Md
Jun 14, 2021
404dabf
initial framework
matthewstern Jun 17, 2021
0f4c869
helper function
matthewstern Jun 17, 2021
e9df8b7
documentation
matthewstern Jun 17, 2021
af17c18
wrapped up with continuous colors
matthewstern Jun 18, 2021
4b1e12b
Update utilities.R
matthewstern Jun 18, 2021
f95c295
discrete palettes
matthewstern Jun 19, 2021
292cb14
race palette
matthewstern Jun 19, 2021
e2b5817
should mostly be working
matthewstern Jun 21, 2021
f9072c2
tweaks
matthewstern Jun 21, 2021
25410d2
typos
matthewstern Jun 21, 2021
09b4812
final tweaks
matthewstern Jun 21, 2021
99be59d
Change default palette from reds to blues
nmpeterson Jun 22, 2021
8daea95
Explicitly name palette types for clearer documentation
nmpeterson Jun 22, 2021
98ae099
Documentation
dlcomeaux Jun 22, 2021
a4333d9
Capitalization/tenses
dlcomeaux Jun 22, 2021
a774e3c
Discrete use of sequential/divergent palettes
dlcomeaux Jun 22, 2021
fbbfb3a
Use prettier palettes for the documentation examples
nmpeterson Jun 22, 2021
68ebb56
Rebuilt help file
nmpeterson Jun 22, 2021
5aac6c1
Delete unneeded line
dlcomeaux Jun 22, 2021
fd2079c
Merge branch 'color_tweaks' of https://github.com/CMAP-REPOS/cmapplot…
dlcomeaux Jun 22, 2021
d0898e3
final tweaks
matthewstern Jun 22, 2021
eee80b7
A few more tweaks
nmpeterson Jun 22, 2021
74f7bfe
Merge pull request #135 from CMAP-REPOS/color_tweaks
matthewstern Jun 24, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions .github/workflows/pkgdown.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Automatically rebuilds pkgdown website any time master branch is updated.
# Also builds pkgdown on "gh-pages-test" on commits to pull requests.
# Based on <https://github.com/r-lib/actions/blob/master/examples/pkgdown.yaml>.
# Conditional based on <https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables>.
on:
push:
branches: master
pull_request:

name: pkgdown

Expand Down Expand Up @@ -56,18 +59,32 @@ jobs:
install.packages("pkgdown")
shell: Rscript {0}

- name: Check Whitney availability
- name: Check Whitney availability in R
run: |
message(paste(sysfonts::font_paths(), collapse = "\n"))
all_fonts <- sysfonts::font_files()
message(paste(all_fonts[all_fonts$family %in% c("Whitney Medium", "Whitney Book", "Whitney Semibold") & all_fonts$face=="Regular", "file"], collapse = "\n"))
all_fonts <- systemfonts::system_fonts()
message("WHITNEY FONTS AUTOMATICALLY AVAILABLE TO SYSTEMFONTS:")
message(paste(all_fonts$name[grepl("^Whitney", all_fonts$name)], collapse = "\n"))
user_dir <- paste0(Sys.getenv("HOME"), "/Library/Fonts")
library_fonts <- list.files(user_dir)
message(paste0("WHITNEY FONTS IN ", user_dir, " (MUST BE REGISTERED):"))
message(paste(library_fonts[grepl("^Whitney", library_fonts)], collapse = "\n"))
shell: Rscript {0}

- name: Install package
run: R CMD INSTALL .

- name: Deploy package
- name: Deploy package to live branch
if: ${{ github.ref == 'refs/heads/main' }}
run: |
echo "This is $GITHUB_REF. Deploying to gh-pages branch."
git config --local user.email "[email protected]"
git config --local user.name "GitHub Actions"
Rscript -e 'pkgdown::deploy_to_branch(new_process = FALSE, clean = TRUE)'
Rscript -e 'pkgdown::deploy_to_branch(clean = TRUE)'

- name: Deploy package to test branch
if: ${{ github.ref != 'refs/heads/main' }}
run: |
echo "This is $GITHUB_REF. Deploying to gh-pages-test branch."
git config --local user.email "[email protected]"
git config --local user.name "GitHub Actions"
Rscript -e 'pkgdown::deploy_to_branch(branch="gh-pages-test", clean = TRUE)'
14 changes: 7 additions & 7 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: cmapplot
Title: CMAP Themes and Color Palettes
Version: 1.1.0
Version: 1.2.0
Authors@R: c(
person("Matthew", "Stern",
role = c("aut", "cre"),
Expand All @@ -24,7 +24,7 @@ Authors@R: c(
role = "aut",
email = "[email protected]"),
person("Chicago Metropolitan Agency for Planning",
role = "cph"))
role = c("cph", "fnd")))
Description: Provides themes and color scales for 'ggplot2', based on Chicago
Metropolitan Agency for Planning (CMAP) design guidelines.
URL: https://cmap-repos.github.io/cmapplot, https://github.com/CMAP-REPOS/cmapplot
Expand All @@ -45,20 +45,20 @@ Imports:
grid,
gridExtra,
gridtext,
lubridate,
magrittr,
purrr,
ragg,
rlang,
rstudioapi,
scales,
stringr,
sysfonts
systemfonts,
tibble
Suggests:
knitr,
lubridate,
readxl,
RCurl,
rmarkdown,
testthat,
tibble,
tidyverse
RoxygenNote: 7.1.1
VignetteBuilder: knitr
21 changes: 16 additions & 5 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export(GeomPointLast)
export(GeomRecessions)
export(GeomRecessionsText)
export(GeomTextLast)
export(abbr_years)
export(apply_cmap_default_aes)
export(cmap_color_continuous)
export(cmap_color_discrete)
Expand All @@ -18,14 +19,14 @@ export(cmap_fill_continuous)
export(cmap_fill_discrete)
export(cmap_fill_highlight)
export(cmap_fill_race)
export(cmap_gradients)
export(cmap_palettes)
export(cmapplot_globals)
export(fetch_pal)
export(finalize_plot)
export(geom_recessions)
export(geom_text_lastonly)
export(get_cmapplot_global)
export(get_cmapplot_globals)
export(gg_lwd_convert)
export(integer_breaks)
export(set_cmapplot_global)
export(theme_cmap)
export(unapply_cmap_default_aes)
export(update_recessions)
Expand All @@ -37,17 +38,27 @@ import(grDevices)
import(graphics)
import(grid)
import(gridtext)
import(ragg)
import(rlang)
import(rstudioapi)
import(scales)
import(systemfonts)
importFrom(generics,intersect)
importFrom(ggpubr,get_legend)
importFrom(glue,glue)
importFrom(glue,glue_collapse)
importFrom(gridExtra,arrangeGrob)
importFrom(lubridate,day)
importFrom(lubridate,decimal_date)
importFrom(lubridate,month)
importFrom(lubridate,year)
importFrom(purrr,compact)
importFrom(purrr,map)
importFrom(purrr,walk2)
importFrom(stats,na.omit)
importFrom(stringr,str_length)
importFrom(stringr,str_replace)
importFrom(stringr,str_trunc)
importFrom(sysfonts,font_files)
importFrom(tibble,tribble)
importFrom(utils,modifyList)
importFrom(utils,read.csv)
31 changes: 31 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
# cmapplot 1.2.0
PR # 123

This is a version-level update that includes many fixes and new features and introduces new dependencies, most significantly RStudio 1.4 or greater.

### New features
* cmapplot now utilizes the new systemfonts package for custom font rendering, rather than sysfonts on Windows and X11fonts on Mac and other Unix-based machines. In addition, raster exports from `finalize_plot` now rely on the new raster drawing package ragg. These changes improve font accuracy and consistency across platforms. Note that this improvement does not yet extend to svg outputs, but may in the future (#134).
* When an axis breaks are 4-digit years, new function `abbr_years` allows the conversion of specific years to 2-digit abbreviations, as is common on some designed CMAP graphics.
* `cmapplot_globals`, which contains key package constants, is now an internal environment rather than an exported list. It can be accessed via new functions `get_cmapplot_globals` and `get_cmapplot_global`. Constants can now be overridden by the user for the current session by using `set_cmapplot_global`. Note that this does not yet apply to geom aesthetics set by the package, but may in the future (issue #117).
* All palettes programmed into the package have been moved into a tibble at `cmapplot_globals$palettes`. A new function `fetch_pal` can be used to get details about any specific palette.

### Bug fixes
* Continuous color gradients can now be used on discrete color scales. E.g. `cmap_color_discrete` and `cmap_fill_discrete` can now call gradients as well as discrete palettes (see #70 and #119)
* Nomenclature in help files (e.g. "palette" vs "scale") has been adjusted for clarity.
* internal table `recessions` has been updated to include the business cycle contraction that began in Feb 202 (no end date for this cycle yet).
* `geom_recessions` and related `update_recessions` have been updated to allow for ongoing recessions, improve NBER source for recessions table, and decrease likelihood of data fetch errors.

### Backend changes
* pkgdown site now correctly displays Whitney fonts and margin description images
* backend script reorganization
* improvements to pkgdown build github action, including ability to publish a test site

### Backward compatibility notes
* **This package will now only render Whitney Fonts in RStudio when RStudio version >= 1.4**
* `finalize_plot`'s `window` mode has been disabled for now, due to inability to use ragg drivers in independent window devices. Use `mode = "plot"` and click the "Zoom" button in the plot window instead.
* `cmapplot_globals`, the exported list of package constants, has been removed (See new features `set_cmapplot_global` etc)
* Color lists `cmap_palettes` and `cmap_gradients` have been removed (This information has been moved to `cmapplot_globals$palettes`. To access palette colors directly, use, say `fetch_pal("reds")` rather than `cmap_gradients$reds`.
* `viz_palette` and `viz_gradient` now take as a first argument either the name of a palette (e.g. `"reds"`) or the color palette itself (e.g. `fetch_pal("reds")`). `viz_palette(cmap_gradient$reds)` no longer works.
* `integer_breaks` removed from package


# cmapplot 1.1.0
PR #111 | February 24, 2021

Expand Down
124 changes: 124 additions & 0 deletions R/axis_handling.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#'Axis handling helper functions
#'
#'`abbr_years()` is a helper functions that allows users to abbreviate year
#'labels to their two-digit representation (e.g., 2008 to '08), but not
#'abbreviate any specified breaks. It does so by creating a new function that
#'takes the breaks supplied by \code{ggplot2} as its only argument. The
#'function was modeled after the syntax and approach of the labeling functions
#'in the \code{scales::label_*} family.
#'
#'@importFrom stringr str_length
#'@importFrom lubridate year month day
#'@importFrom stats na.omit
#'
#'@examples
#'
#'# basic functionality
#'abbr_years()(c(2010:2020))
#'abbr_years(full_by_year = 2000)(c(1990:2010))
#'
#'
#' # Default implementation - this will abbreviate all labels except the first
#' # for both continuous and date scales.
#'
#' df2 <- dplyr::mutate(transit_ridership, year2 = as.Date(lubridate::date_decimal(year)))
#' df1 <- dplyr::filter(df2, year >= 2000)
#'
#' ggplot(df1,
#' aes(x = year, y = ridership, color = system)) +
#' geom_line() +
#' scale_x_continuous(labels = abbr_years())
#'
#' ggplot(df1,
#' aes(x = year2, y = ridership, color = system)) +
#' geom_line() +
#' scale_x_date(labels = abbr_years(dateaxis = TRUE))
#'
#' # If customizations are desired, users can use \code{full_by_pos} and/or
#' # \code{full_by_year} to maintain the full version of the specified labels.
#'
#' ggplot(df2,
#' aes(x = year2, y = ridership, color = system)) +
#' geom_line() +
#' scale_x_date(labels = abbr_years(full_by_year = c(2000), dateaxis = TRUE))
#'
#' # You can also remove the default maintenance of the first label and only
#' # specify specific years.
#' ggplot(df2,
#' aes(x = year, y = ridership, color = system)) +
#' geom_line() +
#' scale_x_continuous(labels = abbr_years(full_by_pos = NULL,
#' full_by_year = c(1990,2020)))
#'
#'
#'@param full_by_pos Vector of integers, the position of breaks that should not
#' be abbreviated. This defaults to \code{c(1)}, which retains the original
#' first label and abbreviates subsequent ones. If all breaks should be
#' abbreviated, this can be set to NULL.
#'@param full_by_year Vector of integers, the value of breaks that should not be
#' abbreviated. Defaults to NULL.
#'@param dateaxis Bool. \code{FALSE}, the default, directs the function to treat
#' the breaks as integers. If set to \code{TRUE} the function will instead
#' treat the breaks as date objects. \code{TRUE} should be used when called
#' within a \code{scale_*_date} ggplot element.
#'
#'@export
abbr_years <- function(full_by_pos = c(1),
full_by_year = NULL,
dateaxis = FALSE) {

fxn <- function(breaks) {

# If a date axis, breaks are stored by ggplot as the number of days since
# the origin date of January 1, 1970. These must be converted to integer
# years, but this should error if all breaks don't fall on the same calendar
# day of a distinct year.
if (dateaxis) {
dates <- as.Date(breaks, origin = "1970-01-01")

if (length(unique(month(stats::na.omit(dates)))) != 1 |
length(unique(day(stats::na.omit(dates)))) != 1) {
message(paste(
paste("Currently, breaks are:", paste(dates[!is.na(dates)], collapse = ", ")),
"This function only works if all breaks are on identical calendar days.",
sep = "\n")
)
stop("Breaks cannot be abbreviated.", call. = FALSE)
}

breaks <- lubridate::year(dates)
}

# Stop if the breaks are not in a four-digit format.
if (!all(stringr::str_length(breaks) == 4, na.rm = TRUE)) {
message(paste(
paste("Currently, breaks are:", paste(breaks[!is.na(breaks)], collapse = ", ")),
"Remove any breaks that contain decimals. Consider `breaks = scales::pretty_breaks()`",
"If the axis is in date format, use `abbr_years(dateaxis = TRUE)`.",
sep = "\n")
)
stop("Breaks cannot be abbreviated.", call. = FALSE)
}

# Abbreviate all values
abbr <- paste0("'",substr(breaks,3,4))

# If there is a leading NA, increment up positions accordingly
leading_na <- which.min(is.na(breaks)) - 1
if(!is.null(full_by_pos)) {
full_by_pos <- full_by_pos + leading_na
}

# Convert specified years into positions
if(!is.null(full_by_year)) {
full_by_pos <- sort(unique(c(full_by_pos,match(full_by_year,breaks))))
}

# Add back full years for specified positions
abbr[full_by_pos] <- breaks[full_by_pos]

return(abbr)
}

return(fxn)
}
Loading