Skip to content
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

Automatically determine prefix and suffix from tags #172

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
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
51 changes: 43 additions & 8 deletions R/plot_annotation.R
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,34 @@ ggplot_add.plot_annotation <- function(object, plot, object_name) {
#' @importFrom utils as.roman
recurse_tags <- function(x, levels, prefix, suffix, sep, offset = 1) {
if (length(levels) == 0) return(list(patches = x, tab_ind = offset))
level <- switch(
as.character(levels[1]),
a = letters,
A = LETTERS,
"1" = 1:100,
i = tolower(as.roman(1:100)),
I = as.roman(1:100),

levels <- as.character(levels[1])
if (grepl("a", levels)) {
level <- letters
} else if (grepl("A", levels)) {
level <- LETTERS
} else if (grepl("1", levels)) {
level <- 1:100
} else if (grepl("i", levels)) {
level <- tolower(as.roman(1:100))
} else if (grepl("I", levels)) {
level <- as.roman(1:100)
} else {
stop('Unknown tag type: ', levels[1], call. = FALSE)
)
}

if (prefix == "" && nchar(levels > 1)) {
index <- find_index_substr(levels, as.character(level[1]))
if (index > 1) {
prefix <- substr(levels, 1, index - 1)
}
}

if (suffix == "" && nchar(levels > 1)) {
index <- find_index_substr(levels, as.character(level[1]))
suffix <- substr(levels, index + 1, nchar(levels))
}

patches <- x$patches$plots
tag_ind <- offset
for (i in seq_along(patches)) {
Expand Down Expand Up @@ -133,6 +152,22 @@ recurse_tags <- function(x, levels, prefix, suffix, sep, offset = 1) {
tag_ind = tag_ind
)
}
find_index_substr <- function(string, substring) {
index <- 1
match <- FALSE
while (index <= nchar(string) && !match) {
if (substr(string, index, index) == substring) {
match <- TRUE
} else {
index <- index + 1
}
}
if (match) {
return(index)
} else {
return(NA)
}
}
#' @importFrom ggplot2 ggplot labs ggplotGrob
#' @importFrom gtable gtable_add_rows gtable_add_cols
#' @importFrom grid unit
Expand Down