If you want to get the ggplot object (not ggmatrix , as in the case of ggpairs() ), the solution is to melt the data twice and then ggplot with the facet. facet_wrap would be better than facet_grid in limiting the plot area if scales = 'free' .
require(ggplot2) require(dplyr) require(tidyr) gatherpairs <- function(data, ..., xkey = '.xkey', xvalue = '.xvalue', ykey = '.ykey', yvalue = '.yvalue', na.rm = FALSE, convert = FALSE, factor_key = FALSE) { vars <- quos(...) xkey <- enquo(xkey) xvalue <- enquo(xvalue) ykey <- enquo(ykey) yvalue <- enquo(yvalue) data %>% { cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars, na.rm = na.rm, convert = convert, factor_key = factor_key), select(., !!!vars)) } %>% gather(., key = !!ykey, value = !!yvalue, !!!vars, na.rm = na.rm, convert = convert, factor_key = factor_key) } iris %>% gatherpairs(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% { ggplot(., aes(x = .xvalue, y = .yvalue, color = Species)) + geom_point() + geom_smooth(method = 'lm') + facet_wrap(.xkey ~ .ykey, ncol = length(unique(.$.ykey)), scales = 'free', labeller = label_both) + scale_color_brewer(type = 'qual') }

mjktfw Dec 09 '17 at 17:18 2017-12-09 17:18
source share