Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 333
user3389288 Avatar asked Dec 28 '25 19:12

user3389288


2 Answers

The GGally package does a pretty nice pairs plot.

library(GGally)
ggpairs(df)

Pairs Plot

like image 81
Gregor Thomas Avatar answered Dec 31 '25 09:12

Gregor Thomas


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

like image 43
redmode Avatar answered Dec 31 '25 11:12

redmode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!