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

时间:2021-10-06 14:59:34

I have a data set;

我有一个数据集;

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

I want to make a scatter plot on a two dimensional plane, but I want the points colored by if they have A or B. Using plot(params), how would I do that?

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

1 个解决方案

#1


1  

If you create the variable newData as you describe in the question, then it will be a matrix of text. I think that you want the first two columns to be numbers and the last column to be text. In order to mix numbers and text like that, you need a different data structure. A good one to use is a data.frame

如果您在问题中描述创建变量newData,那么它将是一个文本矩阵。我认为你希望前两列是数字,最后一列是文本。为了混合数字和文本,你需要一个不同的数据结构。一个好用的是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

Once you have that, the plot is easy.

一旦你有了,情节就很容易了。

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

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

#1


1  

If you create the variable newData as you describe in the question, then it will be a matrix of text. I think that you want the first two columns to be numbers and the last column to be text. In order to mix numbers and text like that, you need a different data structure. A good one to use is a data.frame

如果您在问题中描述创建变量newData,那么它将是一个文本矩阵。我认为你希望前两列是数字,最后一列是文本。为了混合数字和文本,你需要一个不同的数据结构。一个好用的是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

Once you have that, the plot is easy.

一旦你有了,情节就很容易了。

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

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