Basically, I'm trying to add a second legend to a ggpairs
plot. In the example plot below, I am using the iris data and running a randomForest
to get the predictions. I am plotting the density on the diagonal, a scatterplot in the lower triangle and I'm plotting the correlation in the upper triangle. I am colouring the densities and scatterplot by the randomForest
predictions. However, I am colouring the correlation grid using a custom function (found here).
I was wondering if it's possible to have a legend displaying the Species (this part is in the code below) and a legend showing the correlation colours. It is the latter part that I'm having trouble with.
library(randomForest)
library(GGally)
# Get data
ir <- iris
# Create randomForest
rf <- randomForest::randomForest(Species~., data = ir)
pred <- rf$predicted
# Remove Species for plotting
ir <- ir[,-5]
# function to colour corr plot
my_fn <- function(data, mapping, method="p", use="pairwise", ...){
# grab data
x <- eval_data_col(data, mapping$x)
y <- eval_data_col(data, mapping$y)
# calculate correlation
corr <- cor(x, y, method=method, use=use)
# calculate colour based on correlation value
colFn <- colorRampPalette(c("dodgerblue4", "floralwhite", "firebrick1"), interpolate ='spline')
fill <- colFn(100)[findInterval(corr, seq(-1, 1, length=100))]
#make plot
ggally_cor(data = data, mapping = mapping, ...) +
theme_void() +
theme(panel.background = element_rect(fill=fill), panel.border=element_blank(), axis.line=element_line(),
strip.text = element_text(face="bold", colour="red", size = 5))
}
p <- ggpairs(ir,
mapping=ggplot2::aes(colour = pred), legend = 1,
upper=list(continuous = my_fn),
diag = list(continuous = "densityDiag"),
lower=list(continuous=wrap("points", size=.2))) +
theme(panel.border=element_blank(), axis.line=element_line(),
strip.text = element_text(face="bold", colour="red", size = 5))
p
This results in something that will look like this:
Is it possible to add a second legend that corresponds to the correlation plot colours? In my example 1 = red, 0 = white, and -1 = blue for the correlation plot.
EDIT[Still trying to solve this one, if anyone has any suggestions, it would be great]