-2

Dear stackoverflow Community,

I have a vector with different correlation values, which I want to link to corresponding color codes (let's say -1="Dark Red", 0 ="Light Gray", 1="Dark Green"). So, for example, if my maximum value in the correlation would be 0.75, the corresponding color value should be a "Lighter green". Is there any solution to achieve this in R?

Thank you!

hrng
  • 51
  • 7
  • Florian, please provide a reproducible example. Anyway, I suggest in advance that you search for `ggplot2` and `scale_color_manual`. – bbiasi May 04 '19 at 13:48
  • I agree with @bbiasi that you need a reproducible example. Please take a look at [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for information on how to edit your question to include your data. However, if I recall correctly, `ggplot2::scale_color_manual()` won't be of much help as it's used for discrete data rather than continuous. – duckmayr May 04 '19 at 14:18

1 Answers1

0

What you're looking for is ggplot2::scale_colour_gradient2(). Since you didn't provide any example data (which I highly recommend in the future; it encourages answers and helps answerers tailor their responses to your actual data structure), I concocted the following simple example:

library(ggplot2)
set.seed(123)
n <- 1000
corrs <- seq(-0.9, 0.9, length.out = 10)
vals <- matrix(0, nrow = 0, ncol = 2)
for ( corr in corrs ) {
    tmp <- mvtnorm::rmvnorm(n/10, sigma = matrix(c(1, corr, corr, 1), nrow = 2))
    # print(cor(tmp)) # If you want to do QA
    vals <- rbind(vals, tmp)
}
df <- data.frame(var1 = vals[ , 1], var2 = vals[ , 2],
                 corr = rep(corrs, each = n/10))
ggplot(df, aes(x = var1, y = var2, colour = corr)) +
    geom_point(shape = 1) +
    scale_colour_gradient2(low = "darkred", mid = "gray", high = "darkgreen")

enter image description here

duckmayr
  • 16,303
  • 3
  • 35
  • 53