2

I'm trying to do all pairwise scatterplots of a single variable using ggplot2. Something similar to the default pairs(), but I'd like to manipulate the faceting and coloring with ggplot2. here is a failing example of my current attempt in ggplot2

iris_melt = melt(iris)
ggplot(iris_melt, aes(value,value)) + geom_point() + facet_wrap(variable~variable)

enter image description here

What I would like is a plot of:

  • Sepal.Length vs Sepal.Width
  • Sepal.Length vs Petal.Length
  • etc.

I know ggpairs from GGally would do the trick in this situation, however I'd like to do custom faceting and I don't see why I'd need to 'unmelt' the data instead of keeping it tidy

kmace
  • 1,994
  • 3
  • 23
  • 39

3 Answers3

2

There is already a built-in function

 library(GGally)
 ggpairs(iris)
adaien
  • 1,932
  • 1
  • 12
  • 26
  • I guess I'm trying to teach myself ggplot, and I thought that a 'tidy', or melted data frame was always the way to go. with ggpairs i need to 'unmelt' the data. – kmace Mar 29 '16 at 15:09
  • I understand that but this approach is suggested by the package author as well. Melting the data frame is sometimes very useful with `ggplot2` but this is not the case – adaien Mar 29 '16 at 15:29
2

You can supply a custom function to ggpairs which allows you to control all the usual ggplot parameters

df <- read.table("test.txt")

upperfun <- function(data,mapping){
  ggplot(data = data, mapping = mapping)+
    geom_density2d()+
    scale_x_continuous(limits = c(-1.5,1.5))+
    scale_y_continuous(limits = c(-1.5,1.5))
}   

lowerfun <- function(data,mapping){
  ggplot(data = data, mapping = mapping)+
    geom_point()+
    scale_x_continuous(limits = c(-1.5,1.5))+
    scale_y_continuous(limits = c(-1.5,1.5))
}  


ggpairs(df,upper = list(continuous = wrap(upperfun)),
        lower = list(continuous = wrap(lowerfun)))   

See this question for the data and context

see24
  • 1,097
  • 10
  • 21
-1

Another post on stack overflow suggests that you enumerate the data, making an additional column for each comparison:

Faceting plots by combinations of columns in ggplot2

This gets what I want, but its definitely not elegant when doing pairwise combinations between multiple columns.

Community
  • 1
  • 1
kmace
  • 1,994
  • 3
  • 23
  • 39