4
votes

I am wondering if it is possible to assign point colours according both x, and y values in ggplot2?

For instance, I want to assign points, which (x < 0.75 & y < 2) red; which (0.75 <= x & 2 <= y < 4) blue; and which (0.75 <= x & y >= 4) green.

I know it can be done by subsetting the data frame, and then plot them together, but I am wondering if there is a simple way.

library(ggplot2)
data("iris")
ggplot() + geom_point(data = iris, aes(x = Petal.Width, 
                      y = Petal.Length))

enter image description here

3
Make a custom colour column based on conditions, something like: myData$myCol <- ifelse(x..., "red", ifelse(...., "blue", ...))), then use that column within aes col = myCol, and use scale_colour_identity().zx8754
Careful with those conditions, for example when you say (2.25 <= x, y >= 4) are green. do you mean 2.25 <= x AND y >= 4 or 2.25 <= x OR y >= 4? because what you marked as green points there do not fit the first case. And the optimal way I can think of is adding a column to your data with you group specification and then plotting.DS_UNI
@DS_UNI, Thanks, I mean "and", I have edited my question.Wang
@zx8754 thanks a lot for your help.Wang
@Dong in this case the iris dataset would have four groups and not three, I'll post as an answer a sample code for you to tryDS_UNI

3 Answers

2
votes

To extend my comment, make custom colour column based on conditions and use col argument with scale_colour_identity:

library(ggplot2)

# Make a custom colour column based on conditions
# here I used one condition, you can keep nesting ifelse for more conditions
iris$myCol <- ifelse(iris$Petal.Width < 0.75 & iris$Petal.Length, "red", "green")

ggplot(iris) + 
  geom_point(data = iris, 
             aes(x = Petal.Width, y = Petal.Length, col = myCol)) +
  scale_colour_identity()
2
votes

Try this:

library(dplyr)
library(ggplot2)

my_data <- iris %>% 
  mutate(width_length = paste0(cut(Petal.Width, c(0, 0.75, 2.25, Inf), right=FALSE), ' _ ',
                              cut(Petal.Length, c(0, 2, 4, Inf), right=FALSE)))
ggplot(my_data) + 
  geom_point(aes(x = Petal.Width, 
                 y = Petal.Length, 
                 color = width_length))

Output: enter image description here

1
votes

If you need this coloring information only once, just extend iris with this variable temporarily immediately before plotting, making for IMHO cleaner code.

library(dplyr)
library(ggplot2)

iris %>%
    mutate(width_length = 
        paste0(cut(Petal.Width, c(0, 0.75, 2.25, Inf), right=FALSE), 
        ' _ ',
        cut(Petal.Length, c(0, 2, 4, Inf), right=FALSE)))
ggplot() + 
    geom_point(aes(x = Petal.Width, 
             y = Petal.Length, 
             color = width_length))   

This way, you are not messing you workspace which one more dataframe which is used just one, but kept nevertheless.