Created
September 4, 2019 17:27
-
-
Save joelnitta/a2d19d723540dd72e2afaea55a6d17cf to your computer and use it in GitHub Desktop.
Scale a color palette centered on zero
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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