1

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 :)

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
ting_H
  • 83
  • 6
  • 1
    Does this answer your question? [Changing the shape of one point or few points in a scatter plot in R](https://stackoverflow.com/questions/67652479/changing-the-shape-of-one-point-or-few-points-in-a-scatter-plot-in-r) – user438383 Jul 17 '21 at 14:38
  • 1
    A little bit complicated but yes! ^^ – ting_H Jul 18 '21 at 15:05

2 Answers2

1

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

Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

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

bird
  • 2,938
  • 1
  • 6
  • 27