Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
Jack Arnestad Avatar asked Dec 17 '25 17:12

Jack Arnestad


1 Answers

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

like image 158
d.b Avatar answered Dec 20 '25 06:12

d.b



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!