如何根据行创建不同颜色的R散点图?

时间:2020-03-22 10:23:49

标签: r colors scatter-plot

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

enter image description here

我想做一个散点图,其中第1至3行的点是红色,其余行的点是蓝色。我该如何修改代码?

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

3 个答案:

答案 0 :(得分:1)

如果您对前三行的颜色感到满意,可以使用以下方法:

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)

答案 1 :(得分:1)

其他选项

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

答案 2 :(得分:1)

通常,您可以先初始化一个空的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"))

enter image description here


数据

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