两个数据帧之间所有成对列的散点图

时间:2016-11-06 21:22:40

标签: r

假设我有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

执行此操作

2 个答案:

答案 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)

enter image description here

如果你只想创建两个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])
  }
}

enter image description here

答案 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

enter image description here