【问题标题】:How can I make a scatterplot in R with different colours depending on the row?如何根据行在 R 中制作具有不同颜色的散点图?
【发布时间】:2020-07-03 00:10:24
【问题描述】:

我在 RStudio 中导入了以下数据集

我想制作一个散点图,其中第 1 到第 3 行的点为红色,其余行的点为蓝色。请问如何修改代码?

 plot(x=dataset$`col1`,y=dataset$col2, xlab="col1", ylab="col2",pch=16)

【问题讨论】:

    标签: r colors scatter-plot


    【解决方案1】:

    如果您对将前 3 行涂成红色感到满意,您可以使用:

    dataset <- data.frame(col1 = 1:5,
                          col2 = 1,
                          row.names = c("a", "b", "c", "d", "e"))
    
    
    my_colors <- c(rep("red", 3), # first 3 red
                   rep("blue", nrow(dataset) - 3)) # rest is blue
    plot(x = dataset$col1,
         y = dataset$col2, 
         xlab = "col1", 
         ylab = "col2",
         pch = 16, 
         col = my_colors)
    

    【讨论】:

      【解决方案2】:

      附加选项

      library(tidyverse)
      set.seed(0)
      df <- tibble(
        col1 = runif(5),
        col2 = runif(5)
        ) %>% 
        mutate(grp = row_number()<= 3)
      
      ggplot(df, aes(col1, col2, color = grp)) +
        geom_point() +
        scale_color_manual(values = c("red", "blue")) +
        theme(legend.position = "none")
      

      【讨论】:

        【解决方案3】:

        更一般地,您可以初始化一个空的plot,然后在具有所需颜色的相应子集上初始化points

        with(dataset, plot(col1, col2, xlab="col1", ylab="col2", type="n"))
        with(dataset[1:3, ], points(col1, col2, pch=16, col="red"))
        with(dataset[-(1:3), ], points(col1, col2, pch=16, col="blue"))
        


        数据

        dataset <- structure(list(col1 = 1:5, col2 = c(1, 1, 1, 1, 1)), class = "data.frame", row.names = c("a", 
        "b", "c", "d", "e"))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-20
          • 2019-11-03
          • 2021-06-06
          • 1970-01-01
          • 2017-09-14
          • 2012-05-01
          • 1970-01-01
          • 2021-07-13
          相关资源
          最近更新 更多