Search code examples
rr-corrplot

Drawing rectangles in corrplot using corrRect not working when using a mixed plot


I can draw rectangles in a normal correlation matrix using corrplot, e.g.:

library(corrplot) 
corrplot(cor(mtcars)) %>%
corrRect(name = c("mpg", "qsec", "carb"))

But when using this mixed corrplot:

corrplot.mixed(cor(mtcars)) %>%
corrRect(name = c("mpg", "qsec", "carb"))

I get this error message:

Error in if (type == "upper") { : argument is of length zero

How to make it work in a mixed corrplot?


Solution

  • The source for corrRect contains the line if (type == "upper"). type is defined in the function as type = corrRes$arg$type, where corrRes is the correlation plot you pass in the first argument.

    The first plot you created has the type property (run corrplot(cor(mtcars))$arg$type and the output will be "full").

    However, plots created with corrplot.mixed() do not have a value for $arg$type. So we need to create one.

    As your correlation plot is not an upper (or lower) triangular plot, we can assign the value "full" to type. This will allow you to get past the if() statement which causes an error and does not relate to your plot, and to ultimately create the rectangles in the same place.

    p  <- corrplot.mixed(cor(mtcars), tl.pos = "lt")
    p$arg$type  <- "full"
    corrRect(p, name = c("mpg", "qsec", "carb"))
    

    Note: make sure to set tl.pos = "lt" to show the text labels. You can change diag = "l" if you want to show the correlation of 1.00 of every column with itself, rather than having a blank square.

    Output

    enter image description here