在 R 中,如何让散点图根据另一个变量的值为一个点选择颜色?

in R, how do I have the scatterplot choose a color for a point based on the value of another variable?

我有一个数据集;

newData <- cbind(c(1,2,3,4,5),c(6,7,8,9,10),c(A,B,A,B,B))

我想在二维平面上绘制散点图,但如果点有 A 或 B,我想用它们着色。使用 plot(params),我该怎么做?

如果您按照问题中的描述创建变量 newData,那么它将是 text 的矩阵。我认为您希望前两列是数字,最后一列是文本。为了像那样混合数字和文本,您需要不同的数据结构。一个很好用的是 data.frame

newData <- data.frame(V1 = c(1,2,3,4,5),
    V2 = c(6,7,8,9,10), V3 = c('A','B','A','B','B'))
newData
  V1 V2 V3
1  1  6  A
2  2  7  B
3  3  8  A
4  4  9  B
5  5 10  B

有了这些之后,情节就很简单了。

plot(newData[,1:2], pch=20, col=c("red", "blue")[newData$V3])