是否可以使用 ggplot2 绘制散点图矩阵,使用 ggplot 的漂亮功能,例如将其他因素映射到颜色,形状等,并添加更平滑的?
ggplot2
ggplot
我正在考虑类似于 base 函数 pairs 的东西 .
base
pairs
您可能想尝试plotmatrix:
library(ggplot2) data(mtcars) plotmatrix(mtcars[,1:3])
对我来说mpg(mtcars中的第一列)不应该是一个因素 . 我没有检查过,但没有理由为什么它应该是一个 . 但是我得到了散点图:)
Note: 为了将来参考, plotmatrix() 函数已被 GGally 函数替换为 ggpairs() 函数,因为@ naught101建议in another response below来回答这个问题 .
plotmatrix()
GGally
ggpairs()
我一直想做这个,但plotmatrix是废话 . Hadley recommends使用GGally package代替 . 它有一个函数,ggpairs是一个极大改进的对图(允许你在数据框中使用非连续变量) . 它根据变量类型绘制每个方块中的不同图:
library(GGally) ggpairs(iris, aes(colour = Species, alpha = 0.4))
如果想要获得一个 ggplot 对象(不是 ggmatrix ,如 ggpairs() 的情况),解决方案是将数据融合两次,然后使用facetting进行 ggplot . 在给定 scales = 'free' 参数的情况下, facet_wrap 在限制绘制区域方面优于 facet_grid .
ggmatrix
scales = 'free'
facet_wrap
facet_grid
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') }
3 回答
您可能想尝试plotmatrix:
对我来说mpg(mtcars中的第一列)不应该是一个因素 . 我没有检查过,但没有理由为什么它应该是一个 . 但是我得到了散点图:)
Note: 为了将来参考,
plotmatrix()
函数已被GGally
函数替换为ggpairs()
函数,因为@ naught101建议in another response below来回答这个问题 .我一直想做这个,但plotmatrix是废话 . Hadley recommends使用GGally package代替 . 它有一个函数,ggpairs是一个极大改进的对图(允许你在数据框中使用非连续变量) . 它根据变量类型绘制每个方块中的不同图:
如果想要获得一个
ggplot
对象(不是ggmatrix
,如ggpairs()
的情况),解决方案是将数据融合两次,然后使用facetting进行ggplot
. 在给定scales = 'free'
参数的情况下,facet_wrap
在限制绘制区域方面优于facet_grid
.