Skip to content

Instantly share code, notes, and snippets.

@joelnitta
Created September 4, 2019 17:27
Show Gist options
  • Save joelnitta/a2d19d723540dd72e2afaea55a6d17cf to your computer and use it in GitHub Desktop.
Save joelnitta/a2d19d723540dd72e2afaea55a6d17cf to your computer and use it in GitHub Desktop.
Scale a color palette centered on zero
# Scale a color palette centered on zero
#' Get the lower, upper, or absolute maximum value
#' of a variable in a dataframe
#'
#' For setting plotting limits manually
#'
#' @param data Dataframe
#' @param var Name of variable (column) in dataframe
#' @param digits Number of digits desired in output
#' @param type Type of limit to calculate: "min" is lower,
#' "max" is upper, and "abs" is the absolute greatest value.
#'
#' @return Number
#'
#' @examples
#' get_limit(mtcars, disp, "max")
get_limit <- function (data, var, type = c("min", "max", "abs"), digits = 2) {
var <- rlang::enquo(var)
switch(type,
max = data %>%
dplyr::pull(!!var) %>%
max(na.rm = TRUE) %>%
magrittr::multiply_by(10^digits) %>% ceiling %>% magrittr::divide_by(10^digits),
min = data %>%
pull(!!var) %>%
min(na.rm = TRUE) %>%
magrittr::multiply_by(10^digits) %>% floor %>% magrittr::divide_by(10^digits),
abs = c(
data %>% dplyr::pull(!!var) %>% max(na.rm = TRUE),
data %>% dplyr::pull(!!var) %>% min(na.rm = TRUE)) %>%
abs %>% max %>%
magrittr::multiply_by(10^digits) %>% ceiling %>% magrittr::divide_by(10^digits)
)
}
library(tidyverse)
library(scico)
data <- tibble(
intensity = rnorm(10),
xpos = 1:10,
ypos = 1:10
)
# Color will be centered on zero regardless of values of `intensity` in the dataframe
ggplot (data, aes(x = xpos, y = ypos, color = intensity)) +
geom_point() +
scale_color_scico(
palette = "vik",
na.value="dark grey",
limits = c(
-get_limit(data, intensity, "abs", 3),
get_limit(data, intensity, "abs", 3)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment