SiH
SiH

Reputation: 1546

Color ggplot based on interaction of two catergorical variables

Here is sample code. I want to color points based on values of flag and choice (there are 4 possible combination since both variables are binary).

library(tidyverse)

x <- runif(10)
y <- runif(10)
z <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
flag <- c(0, 0, 1, 1, 1, 0, 0, 0, 1, 1)
choice <- c(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)

tbl <- tibble(x, y, z, flag, choice)

scatterplot <- ggplot(tbl,
                      aes(x = x,
                          y = y),
                      color = factor(interaction(choice, flag)),
                      size = 1) + 
  geom_point(alpha = 0.7) +
  scale_color_manual(values = c("blue3", "cyan1", "red3", "oran")) +
  facet_grid(z ~ .) + 
  theme_bw() + 
  theme(legend.position = "right") + 
  theme(aspect.ratio = 1) +
  ggtitle("Scatter plot")

scatterplot

Upvotes: 0

Views: 1599

Answers (1)

carrasco
carrasco

Reputation: 176

You have two mistakes:

  1. Set your color attribute inside of aes(). That way, the feature will be used for coloring.
  2. "oran" is not a color, try with http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf (I set it to "orange").

Code

library(tidyverse)

x <- runif(10)
y <- runif(10)
z <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
flag <- c(0, 0, 1, 1, 1, 0, 0, 0, 1, 1)
choice <- c(0, 1, 0, 1, 0, 1, 0, 1, 0, 1)

tbl <- tibble(x, y, z, flag, choice)

scatterplot <- ggplot(tbl,
                      aes(x = x,
                          y = y,
                          color = factor(interaction(choice, flag))),
                      size = 1) + 
  geom_point(alpha = 0.7) +
  scale_color_manual(values = c("blue3", "cyan1", "red3", "orange")) +
  facet_grid(z ~ .) + 
  theme_bw() + 
  theme(legend.position = "right") + 
  theme(aspect.ratio = 1) +
  ggtitle("Scatter plot")

scatterplot

Result

enter image description here

Upvotes: 2

Related Questions