ting_H
ting_H

Reputation: 93

How to draw a scatter plot in two color using plot in R?

I am drawing a scatter plot using plot in r, and I want to show to dot in two colors.

For example, as you can see in the plot, for those x are smaller than 7 (1~6), I want to color them with red; as for those x are larger or equal to 7(7~10), I want to color them with blue.

This is how I set my dataframe.

df = data.frame(x = c(1:10),y = c(15:6))
plot(df$x,df$y,pch = 16)

This is the scatter plot.

enter image description here

Thank you for answering. If you have other solutions(ggplot), please share with me :)

Upvotes: 1

Views: 839

Answers (2)

bird
bird

Reputation: 3294

Using ggplot2:

library(tidyverse)
df %>% 
        mutate(is_smaller = ifelse(x < 7, TRUE, FALSE)) %>% 
        ggplot(aes(x, y, col = is_smaller)) +
        geom_point(show.legend = F) +
        scale_color_manual(values = c("TRUE" = "red", "FALSE" = "blue"))

enter image description here

Upvotes: 0

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

All you need to add is an ifelse command for the col argument:

plot(df$x,df$y,pch = 16, col = ifelse(df$x < 7, "red", "blue"))

enter image description here

Upvotes: 1

Related Questions