I saw these posts GGally::ggpairs plot without gridlines when plotting correlation coefficient use ggpairs to create this plot
After reading I was able to implement
You are not using wrap
correctly -
see the vignette for details. Also for the diagonal you now have to use the function barDiag
(but ggpairs
gives very helpful errors to tell this)
So for your example, we can change the colour
of the points in the lower
panels and the fill
of the bars below
library(GGally)
library(ggplot2)
ggpairs(swiss[1:3],
lower=list(continuous=wrap("smooth", colour="blue")),
diag=list(continuous=wrap("barDiag", fill="blue")))
However, as the colour of the smooth is hard coded (see ggally_smooth
), to change its
colour you need to define you own function to pass. So from here
my_fn <- function(data, mapping, pts=list(), smt=list(), ...){
ggplot(data = data, mapping = mapping, ...) +
do.call(geom_point, pts) +
do.call(geom_smooth, smt)
}
# Plot
ggpairs(swiss[1:4],
lower = list(continuous =
wrap(my_fn,
pts=list(size=2, colour="red"),
smt=list(method="lm", se=F, size=5, colour="blue"))),
diag=list(continuous=wrap("barDiag", fill="blue")))
In a similar way, here is a way to define a new upper correlation function (similar to what you have)
cor_fun <- function(data, mapping, method="pearson", ndp=2, sz=5, stars=TRUE, ...){
x <- eval_data_col(data, mapping$x)
y <- eval_data_col(data, mapping$y)
corr <- cor.test(x, y, method=method)
est <- corr$estimate
lb.size <- sz* abs(est)
if(stars){
stars <- c("***", "**", "*", "")[findInterval(corr$p.value, c(0, 0.001, 0.01, 0.05, 1))]
lbl <- paste0(round(est, ndp), stars)
}else{
lbl <- round(est, ndp)
}
ggplot(data=data, mapping=mapping) +
annotate("text", x=mean(x, na.rm=TRUE), y=mean(y, na.rm=TRUE), label=lbl, size=lb.size,...)+
theme(panel.grid = element_blank())
}
ggpairs(swiss,
lower=list(continuous=wrap("smooth", colour="blue")),
diag=list(continuous=wrap("barDiag", fill="blue")),
upper=list(continuous=cor_fun))