I would like to use the ggcorr
function from GGally
with the RdBu
palette from RColorBrewer
like demonstrated here. But it seems that non of the palettes seems to work. Here is a reproducible example:
devtools::install_github("ggobi/ggally")
library(GGally)
library(RColorBrewer)
df <- mtcars[, c(1,3,4,5,6,7)]
ggcorr(df, label = TRUE)
ggcorr(df, palette = "RdBu", label = TRUE)
ggcorr(df, palette = "RdYlGn", label = TRUE)
ggcorr(df, palette = "Set1", label = TRUE)
Created on 2023-01-07 with reprex v2.0.2
As you can see, I tried some palettes but every time the colors are the same. So I was wondering if anyone knows how to use a palette
in ggcorr
?
If we check the source code, nbreaks
not having a NULL value is needed for evaluation
> ggcorr
function (data, method = c("pairwise", "pearson"), cor_matrix = NULL,
nbreaks = NULL, digits = 2, name = "", low = "#3B9AB2", mid = "#EEEEEE",
high = "#F21A00", midpoint = 0, palette = NULL, geom = "tile",
min_size = 2, max_size = 6, label = FALSE, label_alpha = FALSE,
label_color = "black", label_round = 1, label_size = 4, limits = c(-1,
1), drop = is.null(limits) || identical(limits, FALSE),
layout.exp = 0, legend.position = "right", legend.size = 9,
...)
{
..
..
if (!is.null(nbreaks)) {
x = seq(-1, 1, length.out = nbreaks + 1)
if (!nbreaks%%2) {
x = sort(c(x, 0))
}
m$breaks = cut(m$coefficient, breaks = unique(x), include.lowest = TRUE,
dig.lab = digits)
}
..
..
if (geom == "tile") {
if (is.null(nbreaks)) {
p = p + geom_tile(aes(fill = coefficient), color = "white")
}
else {
p = p + geom_tile(aes(fill = breaks), color = "white")
}
if (is.null(nbreaks) && !is.null(limits)) {
p = p + scale_fill_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint, limits = limits)
}
else if (is.null(nbreaks)) {
p = p + scale_fill_gradient2(name, low = low, mid = mid,
high = high, midpoint = midpoint)
}
else if (is.null(palette)) {
x = colorRampPalette(c(low, mid, high))(length(levels(m$breaks)))
p = p + scale_fill_manual(name, values = x, drop = drop)
}
else {
p = p + scale_fill_brewer(name, palette = palette,
drop = drop)
}
..
}
Also it is specified in documentation
nbreaks - the number of breaks to apply to the correlation coefficients, which results in a categorical color scale.
if nbreaks is used, a ColorBrewer palette to use instead of the colors specified by low, mid and high. Defaults to NULL.
Therefore, we may specify the nbreaks
ggcorr(df, palette = "RdYlGn", label = TRUE, nbreaks = 5)
-output
ggcorr(df, palette = "Set1", label = TRUE, nbreaks = 5)