如何根据行在 R 中制作不同颜色的散点图?
How can I make a scatterplot in R with different colours depending on the row?
我在 RStudio 中导入了以下数据集
我想制作一个散点图,其中第 1 行到第 3 行的点为红色,其余行的点为蓝色。请问我该如何修改代码?
plot(x=dataset$`col1`,y=dataset$col2, xlab="col1", ylab="col2",pch=16)
如果您对将前 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)
附加选项
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")
更一般地说,您可以初始化一个空 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"))
我在 RStudio 中导入了以下数据集
我想制作一个散点图,其中第 1 行到第 3 行的点为红色,其余行的点为蓝色。请问我该如何修改代码?
plot(x=dataset$`col1`,y=dataset$col2, xlab="col1", ylab="col2",pch=16)
如果您对将前 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)
附加选项
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")
更一般地说,您可以初始化一个空 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"))