Search code examples
rcorrelationr-corrplotggcorrplot

How to obtain ideal color scale in corrplot?


I have a matrix that I am trying to visualize using the corrplot package in R. The values in this matrix are fold changes of a treatment group relative to a control group (1 meaning there is no change, >1 meaning treatment group enhanced, <1 meaning treatment group reduced). Is there a way to utilize corrplot such that all values < 1 are on a red gradient, all values > 1 are on a green gradient, and all values = 1 are white?

Here is what I have tried:

Sample data:

testdata = matrix(rnorm(10, 1, 0.1), nrow = 5)
testdata
          [,1]      [,2]
[1,] 1.1368602 1.0123854
[2,] 0.9774229 1.0215942
[3,] 1.1516471 1.0379639
[4,] 0.8451247 0.9497677
[5,] 1.0584614 0.9666793

corrplot(testdata, is.corr = FALSE, col.lim = c(0, max(testdata)))

That produces the following:

Produced Plot

As you can see, there is no demarcation between values > 1 vs < 1. If anyone is able to share any way to set a transition point on the corrplot package that places all values > threshhold as being on one color gradient and all values < threshhold as being on another color gradient I would be extremely grateful! Thank you for your time.

EDIT: Additionally, the values in the matrix range from 0 to >3 but I am still hoping to keep the 'white' transition point of the color legend of the corrplot at 1. If I use the suggestions from the helpful answers below it only works if the range of values in the matrix is between 0 and 2 which sets white transition point of color legend at value of 1. A range of 0 and 3, for example, sets the white transition point at 1.5 whereas I would like it to remain at 1


Solution

  • You could do that with col argument.

    library(corrplot)
    #> corrplot 0.92 loaded
    
    set.seed(123)
    testdata = matrix(rnorm(10, 1, 0.1), nrow = 5)
    corrplot(testdata, 
             is.corr = FALSE, 
             col.lim = c(min(testdata), max(testdata)),
             col = COL2("RdBu"),
             )
    

    Created on 2023-05-03 with reprex v2.0.2

    Edit
    You can manually control gradient range with ggcorrplot. Note that ggcorrplot can be compatible with ggplot2, thus you can use scale_fill_gradient2().

    library(ggcorrplot)
    set.seed(1234)
    testdata = matrix(runif(10, min=0, max=3),nrow=5)
    ggcorrplot(testdata) +
      scale_fill_gradient2(limit = c(0,3), low = "red", high =  "blue", mid = "white", midpoint = 1)
    #> Scale for fill is already present.
    #> Adding another scale for fill, which will replace the existing scale.
    

    Created on 2023-05-03 with reprex v2.0.2