Iterate over columns and plotting them using ggplot

Viewed 41

I have a numeric data frame call A, and I want to make a graph for every two variables (columns) of A.

My try:

x <- unlist(lapply(D, is.numeric))    
A <- D[,x]
for(i in (1:ncol(A)))
{
  for(j in (1:ncol(A)))
  {
    ggplot(algas, aes(x = A[,i], y = A[,j])) +
    geom_point() 
  }
}

But is not plotting anything. I'm not sure if it's necessary to save each plot in a vector and then plot them with another for. Any suggestions would be great!

1 Answers

You could do it this way:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)
dat <- mtcars %>% select(c(1, 3:7))
combs <- combn(names(dat), 2) %>% 
  t() %>% 
  as.data.frame()
plots <- purrr::map2(combs$V1, combs$V2, ~ggplot(dat, aes_string(x=.x, y=.y)) + geom_point())
plots
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

#> 
#> [[4]]

#> 
#> [[5]]

#> 
#> [[6]]

#> 
#> [[7]]

#> 
#> [[8]]

#> 
#> [[9]]

#> 
#> [[10]]

#> 
#> [[11]]

#> 
#> [[12]]

#> 
#> [[13]]

#> 
#> [[14]]

#> 
#> [[15]]

Created on 2022-05-02 by the reprex package (v2.0.1)

You could also try ggpairs() from the GGally package:

library(GGally)
#> Loading required package: ggplot2
#> Registered S3 method overwritten by 'GGally':
#>   method from   
#>   +.gg   ggplot2
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
dat <- mtcars %>% select(c(1, 3:7))
ggpairs(dat)

Created on 2022-05-02 by the reprex package (v2.0.1)

Related