Jack Arnestad
Jack Arnestad

Reputation: 1865

Color each facet by different variable value

I have a data frame like the following:

df = data.frame(x = runif(100, 0, 1),
                y = runif(100, 1, 2),
                var1 = runif(100, 0, 1),
                var2 = runif(100, 0, 1),
                var3 = rep(c("a", "b"), 50))

I want to make a faceted plot in ggplot2 that plots the same x vs y in each facet (scatterplot), but colors by the values of var1, var2, and var3. In this case, there would only be 3 facets, one for each of the coloring columns.

How could this be done?

Upvotes: 3

Views: 201

Answers (1)

d.b
d.b

Reputation: 32538

plots = lapply(3:5, function(i){
    dt = df[,c(1, 2, i)]
    ggplot(data = dt, aes_string(x = names(dt)[1],
                                 y = names(dt)[2],
                                 color = names(dt[3]))) +
        geom_point()
})
library(gridExtra)
do.call(function(...){
    grid.arrange (..., ncol = 3)},
    plots)

Rplot

Upvotes: 3

Related Questions