Search code examples
rplotggplot2facet

Faceting plots by combinations of columns in ggplot2


I am doing combinations of correlations, and would like to plot in ggplot2 each combination. However I want each combination on a separate panel, rather than all the points on one panel.

#making up columns, in my real data I'm doing correlations between each column (ie. col1~col2, col1~col3, col2~col3)
col1 <- c(1:10)
col2 <- c(12:3)
col3 <- c(10, 12, 18, 19, 20, 30, 31, 32, 40, 41)

df <- data.frame(col1, col2, col3)

g <- ggplot(data=df, aes(x=col1, y=col3)) + geom_point()

I knew this wouldn't make my desired plot, but I'm really stumped as to how to approach this in ggplot2. Just to be clear, I want to make three scatter plots in total.

Any help is appreciated!


Solution

  • require(ggplot2)
    
    # Your data
    col1 <- c(1:10)
    col2 <- c(12:3)
    col3 <- c(10, 12, 18, 19, 20, 30, 31, 32, 40, 41)
    
    # Creation of data.frame
    df <- 
      rbind(data.frame(x=col1, y=col2, cor="1-2"),
            data.frame(x=col1, y=col3, cor="1-3"),
            data.frame(x=col2, y=col3, cor="2-3"))
    
    # Plotting
    ggplot(df, aes(x, y)) + geom_point() + facet_wrap(~cor, scales="free")
    

    enter image description here