Create a matrix of scatterplots (pairs() equivalent) in ggplot2
是否可以使用
我正在考虑类似于
我一直想这样做,但plotmatrix很糟糕。 Hadley建议改用GGally软件包。它具有ggpairs函数,这是一个大大改进的对图(让您在数据帧中使用非连续变量)。它根据变量类型在每个正方形中绘制不同的图:
1 2 | library(GGally) ggpairs(iris, aes(colour = Species, alpha = 0.4)) |
您可能想尝试一下plotmatrix:
1 2 3 | library(ggplot2) data(mtcars) plotmatrix(mtcars[,1:3]) |
对我而言,mpg(mtcars的第一列)不应成为一个因素。我没有检查它,但是没有理由为什么它应该是一个。但是我得到了一个散点图:)
注意:为将来参考,已将
如果要获取一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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') } |