I am trying to assign colors to text in a ggpairs plot matrix depending on column correlations (high correlations are red, low ones are blue):
colors <- colorRampPalette(c("blue", "red"))(100)
correlation_color <- function(data, mapping, ...) {
cor = print(cor(data[,toString(mapping$x)], data[,toString(mapping$y)]))
col = colors[round(abs(cor) * 100)]
print(col)
print(class(col))
ggally_text(paste("Cor: ", round(cor, 2), sep = ""), aes(color = col))
}
plt = ggpairs(sales_df,
lower = list(continuous = wrap("smooth", color='blue', size=0.5, method='loess')), diag = list(continuous = wrap("barDiag", binwidth=1, color='blue')),
upper = list(continuous = wrap(correlation_color))
) + theme_light()
plt
First of all, I don't understand why I need to cast mapping$x
to string before subsetting the data frame using it.
Besides that, my code fails with the following error:
Error in .subset(col, i) : object of type 'symbol' is not subsettable
This does not occur when I replace aes(color = col) by aes(color = "red"). I also tried:
ggally_text(paste("Cor: ", round(cor, 2), sep = ""), color = col)
But this produces no color on the text (besides the warning The plyr::rename operation has created duplicates for the following name(s): (
colour)
)
What is happening? The errors/warnings make absolutely no sense to me. What is the type symbol
? Why can't I replace a string with another string? Is there a simpler way to achieve my goal?
EDIT
Here's a minimal nonsensical example dataset:
sales_df <- data.frame(X1=seq(1,9,length.out = 15), X2=1:15)