Closed davidhodge931 closed 5 months ago
library(tidyverse)
library(palmerpenguins)
hold_3rd <- function(x) {
c("", "", as.character(x[2]), rep("", times = length(x) - 3))
}
penguins |>
ggplot() +
geom_point(
aes(x = bill_length_mm,
y = body_mass_g),
) +
scale_x_continuous(labels = \(x) hold_3rd(scales::comma(x)))
penguins |>
ggplot() +
geom_point(
aes(x = flipper_length_mm,
y = body_mass_g),
) +
scale_x_continuous(labels = \(x) hold_3rd(scales::comma(x)))
#' Hold every nth element
#'
#' @description
#' Hold every nth element in a vector, and replace the rest with "".
#'
#' @param x A vector.
#' @param nth The increment of elements to hold as is. Defaults to `2`.
#' @param offset An offset for which element to first hold. Defaults to `0`. Possible values are `-1` to (`nth - 2`)
#'
#' @return A character vector
#' @noRd
#'
#' @examples
#' hold_nth(scales::comma(seq(1000, 5000, 1000)))
#' hold_nth(format(lubridate::ymd(c("2021-01-01", "2022-01-01", "2023-01-01", "2024-01-01"))))
#' hold_nth(LETTERS[1:12])
hold_nth <- function(x,
nth = 2,
offset = 0) {
replace(x, seq_along(x) %% nth != (offset + 1), "")
}
Note that ggplot2 applies labelling function prior to breaks, so the first break is often in a confusing and inconsistent place.
Leave this for now until/unless ggplot2 fixes
Needs to take the breaks only within the limits...
Otherwise, it doesn't work..