1

I'm looking to create a scatterplot within R that has points that are split into four quadrants and then applies a color to each quadrant based on group.

I have used the following code which works, but need to change the colours.

x_mid <- mean(c(max(iris$Petal.Length, na.rm = TRUE), 
                min(iris$Petal.Length, na.rm = TRUE)))

y_mid <- mean(c(max(iris$Petal.Width, na.rm = TRUE), 
                min(iris$Petal.Width, na.rm = TRUE)))
library(dplyr)
library(ggplot2)

iris %>% 
  mutate(quadrant = case_when(Petal.Length > x_mid & Petal.Width > y_mid   ~ "Q1",
                              Petal.Length <= x_mid & Petal.Width > y_mid  ~ "Q2",
                              Petal.Length <= x_mid & Petal.Width <= y_mid ~ "Q3",
                              TRUE                                         ~ "Q4")) %>% 
  ggplot(aes(x = Petal.Length, y = Petal.Width, color = quadrant)) +
  geom_vline(xintercept = x_mid) + # plot vertical line
  geom_hline(yintercept = y_mid) + # plot horizontal line
  geom_point()

1 Answers1

2

If I understood correctly, the only thing that is missing is the manual selection of the colors, in which case the fact that the colors come from quadrants is incidental. Otherwise, I'm afraid I'm missing something.

You can specify the color scale like any other aesthetic. In particular, scale_color_manual lets you give it a vector of strings specifying the colors to use.

So you can add at the end:

scale_color_manual(values = c('orange', 'yellow', 'black', 'grey'))

You you want to map a specific color to each possible level, you can give it a named vector:

  scale_color_manual(values = c(Q4 = 'orange', Q2 = 'yellow', Q1 = 'black', Q3 = 'grey'))
mgiormenti
  • 793
  • 6
  • 14