Closed saisaitian closed 1 year ago
Good question. Automatic color palette extrapolation is a doable feature and has been planned for ggsci 3.0.0. In case I don't have time to work on that this year, here is how it can be done by yourself:
library("ggsci")
#' Adaptive palette (discrete).
#'
#' Create a discrete palette which will use the first n colors from
#' the supplied color values, and interpolate after n.
adaptive_pal <- function(values) {
force(values)
function(n = 10) {
if (n <= length(values)) {
values[seq_len(n)]
} else {
colorRampPalette(values, alpha = TRUE)(n)
}
}
}
pal_npg_adaptive <- function(palette = c("nrc"), alpha = 1) {
palette <- match.arg(palette)
if (alpha > 1L | alpha <= 0L) stop("alpha must be in (0, 1]")
raw_cols <- ggsci:::ggsci_db$"npg"[[palette]]
raw_cols_rgb <- col2rgb(raw_cols)
alpha_cols <- rgb(
raw_cols_rgb[1L, ], raw_cols_rgb[2L, ], raw_cols_rgb[3L, ],
alpha = alpha * 255L, names = names(raw_cols),
maxColorValue = 255L
)
adaptive_pal(unname(alpha_cols))
}
scale_color_npg_adaptive <- function(palette = c("nrc"), alpha = 1, ...) {
palette <- match.arg(palette)
discrete_scale("colour", "npg", pal_npg_adaptive(palette, alpha), ...)
}
scale_fill_npg_adaptive <- function(palette = c("nrc"), alpha = 1, ...) {
palette <- match.arg(palette)
discrete_scale("fill", "npg", pal_npg_adaptive(palette, alpha), ...)
}
library("ggplot2")
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
dsamp$table <- as.factor(dsamp$table)
ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = table)) +
theme_bw() + scale_color_npg_adaptive()
where is discrete_scale
function? could you provide?
Nice function! Will it ever be integrated into the ggsci package? I mean, since you already have the function here
I posted a more generic version of the above code here: https://nanx.me/blog/post/ggplot2-color-interpolation/
I will also look into the possibility to incorporate this into the package in future releases.
Nice function! But how to adjust the order of colors after using the above function?
@zhouyutong123 I guess the main purpose of this is automation. While you can always use any additional logic to adjust the colors (including ordering) in pal_adaptive()
, or simply create a manual color scale and adjust there: https://r-graphics.org/recipe-colors-palette-discrete-manual
Dear authuors:
when I use ggsci, the scale_color_npg() only provied 10 colors,in fact ,I need 15 colors,how can I fix it?