Jika seseorang ingin mendapatkan suatu ggplot
objek (tidak ggmatrix
seperti kasus ggpairs()
), solusinya adalah mencairkan data dua kali, kemudian ggplot
dengan facetting. facet_wrap
akan lebih baik daripada facet_grid
membatasi area yang diplot, mengingat scales = 'free'
parameter disediakan.
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')
}