davidhodge931 / ggblanket

Simplify ggplot2 visualisation
https://davidhodge931.github.io/ggblanket/
Other
156 stars 8 forks source link

hold_nth: hold every nth element and replace the rest with "" #839

Closed davidhodge931 closed 5 months ago

davidhodge931 commented 6 months ago

Needs to take the breaks only within the limits...

Otherwise, it doesn't work..

davidhodge931 commented 6 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)))
davidhodge931 commented 6 months ago
#' 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), "")
}
davidhodge931 commented 6 months ago

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