假设我有2个数据框:
df1 = data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))
df2 = data.frame(d = rnorm(10), e = rnorm(10))
我想看看数据框之间的所有成对散点图:
即:六个散点图:a vs d,a vs e,b vs d,b vs e,c vs d,c vs e。
我怎么能实现这个目标?我注意到pairs
为单个data.frame
答案 0 :(得分:4)
使用cbind
合并两个dfs,然后使用plot()
df1 = data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))
df2 = data.frame(d = rnorm(10), e = rnorm(10))
df <- cbind(df1, df2)
plot(df)
如果你只想创建两个data.frames
之间的图(没有自我比较),你可以循环它们:
par(mfrow = c(ncol(df1), ncol(df2)))
for(i in 1:ncol(df1)){
for(j in 1:ncol(df2)){
plot(df1[,i], df2[,j], main = paste(names(df1)[i], "vs", names(df2)[j]),
ylab = names(df2)[j],
xlab = names(df1)[i])
}
}
答案 1 :(得分:2)
一个漂亮的(不必要的复杂?)tidyverse / ggplot2解决方案。
重组数据:
library(dplyr)
library(tidyr)
mfun <- function(x,label="df1") {
x %>%
mutate(obs=seq(n())) %>% ## add obs numbers
gather(key=var,value=value,-obs) ## reshape
}
## combine
df12 <- mfun(df1) %>% full_join(mfun(df2),by="obs")
简介:
library(ggplot2); theme_set(theme_bw())
ggplot(df12,aes(value.x,value.y)) +
geom_point()+
facet_grid(var.x~var.y)+
theme(panel.margin=grid::unit(0,"lines")) ## squash panels together