2

I have this dataset: https://dl.dropboxusercontent.com/u/73950/data.csv The dataset contains 3 variables.

Here's how I visualize the data right now:

library(ggplot2)
library(reshape2)
library(RColorBrewer)

dat = read.csv("data.csv", header = FALSE)

myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
sc <- scale_colour_gradientn(colours = myPalette(100))

ggplot(dat, aes(x=V1, y=V3, colour = V2))+ geom_point(alpha = .2,size = 3) + sc

Instead of just one figure, I'd like to facet the figure to display 3 different ways to attribute variables to each axis and color. As such:

  • x = V1, y = V2, color = V3
  • x = V1, y = V3, color = V2
  • x = V2, y = V3, color = V1

How to do this kind of things with ggplot2's faceting?

1 Answer 1

3

You can get this by putting the data in the format ggplot likes. In this case, a column that can be used to split the data into facets (called var below). To do that, I just repeated the data three times, choosing the appropriate x and y variables for each 2-way combo, and using the variable left out of each combination as the coloring variable.

## Rearrange the data by 2-way combinations, the coloring is the remaining column
res <- do.call(rbind, combn(1:3, 2, function(ii)
    cbind(setNames(dat[,c(ii, setdiff(1:3, ii))], c("x", "y", "color")),
                   var=paste(ii, collapse=".")), simplify=F))

ggplot(res, aes(x=x, y=y, color=color))+ geom_point(alpha = .2,size = 3) + 
  facet_wrap(~ var, scales="free") + sc

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Fantastic! is it possible to give each of these facet a separate color legend?
@Rodolphe I'm not sure, I was just trying to make sense of the colors, will update if I figure anything out. What you can do easily is put three plots (not facetted) on the same canvas with different legends, but that totally defeats the purpose of this.
@Rodolphe this answer here from hadley, stackoverflow.com/a/3809071/2415684, makes me think a hack might be necessary... Maybe color by distance from each variables mean (by scaleing)? I dont know sry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.