我定义了一个函数来设置ggpairs中的背景,以匹配两个变量之间的相关性水平。 然而,我也想要去掉沿着绘图外部运行的变量标签的灰色背景,但是我没有办法在不同时去掉相关颜色的情况下这样做。
library(GGally)
# Loads some data
mtcars <- dput(mtcars)[,1:6]
# Defines function to color according to correlation
cor_func <- function(data, mapping, method, symbol, ...){
x <- eval_data_col(data, mapping$x)
y <- eval_data_col(data, mapping$y)
corr <- cor(x, y, method=method, use='complete.obs')
colFn <- colorRampPalette(c("brown1", "white", "dodgerblue"),
interpolate ='spline')
fill <- colFn(100)[findInterval(corr, seq(-1, 1, length = 100))]
ggally_text(
label = paste(symbol, as.character(round(corr, 2))),
mapping = aes(),
xP = 0.5, yP = 0.5,
color = 'black',
...) +
theme_void() +
theme(panel.background = element_rect(fill = fill))
}
# Following the suggestion by @Jonni
pm <- ggpairs(mtcars,
upper = list(continuous = wrap(cor_func,
method = 'spearman', symbol = expression('\u03C1 ='))),
lower = list(continuous = function(data, mapping, ...) {
ggally_smooth_lm(data = data, mapping = mapping) +
theme(panel.background = element_blank())}),
diag = list(continuous = function(data, mapping, ...) {
ggally_densityDiag(data = data, mapping = mapping) +
theme(panel.background = element_blank())}
))
pm
# All of these methods looses the correlation color in addition
# to the background color of the labels
pm + theme(strip.background = element_rect(fill = "white"))
pm + theme(strip.background = element_rect(fill = NA))
pm + theme(strip.background = element_blank())
# This only looses the correlation colors
pm + theme(panel.grid.major = element_blank(), panel.grid.minor =
element_blank())
下面是第一次调用plot函数得到的颜色示意图(标签背景仍然是灰色):