Nếu ai muốn có được một đối tượng ggplot
(không ggmatrix
như trong trường hợp của ggpairs()
), giải pháp là để làm tan dữ liệu hai lần, sau đó ggplot
với mặt nạ. facet_wrap
sẽ tốt hơn facet_grid
trong việc giới hạn vùng được vẽ, với tham số scales = 'free'
được cung cấp.
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')
}
Ngoài ra kiểm tra ggally – hadley
Ah, tôi không thấy nhận xét của bạn có hadley. Tôi đã thực hiện câu trả lời của tôi CW để không ăn cắp niềm tin của bạn :) – naught101