0

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)
aosmith
  • 34,856
  • 9
  • 84
  • 118
Gerry
  • 1,938
  • 3
  • 18
  • 25
  • Can you provide some sample data so that we can run this ourselves? – joran Nov 30 '17 at 15:48
  • 1
    You are correct to take `color` outside of `aes`. You need to give a blank `mapping` with `gally_text`, as well: `ggally_text(paste("Cor: ", round(cor, 2), sep = ""), mapping = aes(), color = col)` – aosmith Dec 01 '17 at 16:54
  • Indeed, you are right. Thank you. If you're willing to post an answer I'll gratefully accept it. Out of curiosity, how was I supposed to figure this out from the docs or any online sources? It seems very random to me. – Gerry Dec 04 '17 at 18:57

0 Answers0