Reputation: 93
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.
Thank you for answering. If you have other solutions(ggplot), please share with me :)
Upvotes: 1
Views: 839
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"))
Upvotes: 0
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"))
Upvotes: 1