Last active
February 1, 2023 18:43
-
-
Save mattgalbraith/a5afc8aed39aa28b868f0ffc67aed044 to your computer and use it in GitHub Desktop.
R function to generate 2D Density colors for ggplot
This file contains 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
## Density color function | |
# usage: | |
# tbl |> | |
# mutate(density = getDenCols(x, y, transform = TRUE)) |> # transformation here must match aes() | |
# arrange(density) |> # ensures highest desity points on top | |
# ggplot(aes(log2(x), log2(y), color = density)) + | |
# geom_point() + | |
# scale_color_vididis_c() # works best with viridis | |
getDenCols <- function(x, y, transform = TRUE) { # set to TRUE if using log2 transformation of data | |
if(transform) { | |
df <- data.frame(log2(x), log2(y)) | |
} else{ | |
df <- data.frame(x, y) | |
} | |
z <- grDevices::densCols(df, colramp = grDevices::colorRampPalette(c("black", "white"))) | |
df$dens <- grDevices::col2rgb(z)[1,] + 1L | |
cols <- grDevices::colorRampPalette(c("#000099", "#00FEFF", "#45FE4F","#FCFF00", "#FF9400", "#FF3100"))(256) | |
df$col <- cols[df$dens] | |
return(df$dens) | |
} # End of function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment