我在RStudio中导入了以下数据集
我想做一个散点图,其中第1至3行的点是红色,其余行的点是蓝色。我该如何修改代码?
plot(x=dataset$`col1`,y=dataset$col2, xlab="col1", ylab="col2",pch=16)
答案 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"))
数据
dataset <- structure(list(col1 = 1:5, col2 = c(1, 1, 1, 1, 1)), class = "data.frame", row.names = c("a",
"b", "c", "d", "e"))