Reputation: 2044
lets say I have 2 data frames:
df1 = data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))
df2 = data.frame(d = rnorm(10), e = rnorm(10))
I would like to look at the all pairwise scatter plots between data frames:
i.e.: the six scatter plots: a vs d, a vs e, b vs d, b vs e, c vs d, c vs e.
How could I achieve this? I notice that pairs
does this for a single data.frame
Upvotes: 3
Views: 2831
Reputation: 226771
A pretty (unnecessarily complicated?) tidyverse/ggplot2 solution.
Reorganize data:
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")
Plot:
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
Upvotes: 2
Reputation: 10350
use cbind
to combine the two dfs and then use 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)
If you want to create only plots between the two data.frames
(no self comparison), you can loop them:
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])
}
}
Upvotes: 4