简体   繁体   English

如何使用R中的绘图绘制两种颜色的散点图?

[英]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.我正在使用 r 中的 plot 绘制散点图,并且我想以两种颜色显示点。

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;例如,正如你在图中看到的,对于那些 x 小于 7(1~6)的,我想用红色给它们着色; as for those x are larger or equal to 7(7~10), I want to color them with blue.至于那些 x 大于或等于 7(7~10) 的,我想用蓝色给它们上色。

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 :)如果您有其他解决方案(ggplot),请与我分享:)

All you need to add is an ifelse command for the col argument:您只需要为col参数添加一个ifelse命令:

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

在此处输入图片说明

Using ggplot2 :使用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"))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM