Based on this post, now that I have
library (GGally)
# from help
PointsWithCor <- function(data, mapping, ..., method = "pearson") {
x <- eval(mapping$x, data)
y <- eval(mapping$y, data)
cor <- cor(x, y, method = method)
ggally_points(data, mapping, ...) +
ggplot2::geom_label(
data = data.frame(
x = min(x, na.rm = TRUE),
y = max(y, na.rm = TRUE),
lab = round(cor, digits = 3)
),
mapping = ggplot2::aes(x = x, y = y, label = lab),
hjust = 0, vjust = 1,
size = 5, fontface = "bold",
inherit.aes = FALSE # do not inherit anything from the ...
)
}
# data frame
df = data.frame(runif(100),
rnorm(100),
rgamma(100,1,2),
rt(100,1),
rf(100,1,2),
as.factor(round(runif(100,0,1))))
colnames(df) = c("a","b","c","d","e","f")
# points + cor, but only one cor index
ggduo(df,columnsX = 1:2, columnsY = 3:5,
mapping = aes(colour = f),
types = list(continuous = PointsWithCor))
but it produces a matrix of scatterplot with correlation in all x and all y. I'd like to show correlations colored by the same way to coloring the points in scatterplots.
I think it needs to modify the function to use the colour
attribute in mapping, but not sure how to do it. Could anyone please give me a suggestion?
Edit:
To align the correlation labels in the image in the answer from @aosmith,
# from help but modified
PointsWithCor <- function(data, mapping, ..., method = "pearson") {
df <- data.frame(x = eval(mapping$x, data), y = eval(mapping$y, data), c = eval(mapping$colour, data))
xPos = min(df$x)
yPos = max(df$y)
sumdf <- df %>%
group_by(c) %>%
summarise(
lab = round(cor(x, y),3),
x = xPos,
y = yPos*min(as.numeric(c))/max(as.numeric(df$c))
)
ggally_points(data, mapping, ...) +
ggplot2::geom_label(
data = sumdf,
mapping = ggplot2::aes(x = x, y = y, label = lab, color = c),
hjust = 0, vjust = 1,
size = 5, fontface = "bold",
inherit.aes = FALSE # do not inherit anything from the ...
)
}