【问题标题】:How to draw a scatter plot in two color using plot in R?如何使用 R 中的绘图绘制两种颜色的散点图?
【发布时间】:2021-07-17 14:11:10
【问题描述】:

我正在使用 r 中的绘图绘制散点图,我想用两种颜色显示点。

例如,正如您在图中看到的那样,对于那些 x 小于 7 (1~6),我想将它们涂成红色;至于那些 x 大于等于 7(7~10) 的,我想把它们染成蓝色。

这就是我设置数据框的方式。

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

这是散点图。

感谢您的回答。 如果您有其他解决方案(ggplot),请与我分享:)

【问题讨论】:

标签: r plot


【解决方案1】:

您只需为col 参数添加一个ifelse 命令:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多