如何在R中的散点图中为每个类赋予颜色? [英] How to give color to each class in scatter plot in R?
问题描述
在数据集中,我想采用两个属性并创建监督的散点图.有谁知道如何给每个班级使用不同的颜色?
In a dataset, I want to take two attributes and create supervised scatter plot. Does anyone know how to give different color to each class ?
我正在尝试在plot命令中使用col == c("red","blue","yellow")
,但是不确定是否像我再添加一种颜色一样正确,即使我只有3个类,该颜色也会出现在散点图中.
I am trying to use col == c("red","blue","yellow")
in the plot command but not sure if it is right as if I include one more color, that color also comes in the scatter plot even though I have only 3 classes.
谢谢
推荐答案
以下是使用传统图形(和Dirk的数据)的解决方案:
Here is a solution using traditional graphics (and Dirk's data):
> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE))
> DF
x y z
1 1 6.628380 c
2 2 6.403279 b
3 3 6.708716 a
4 4 7.011677 c
5 5 6.363794 a
6 6 5.912945 b
7 7 2.996335 a
8 8 5.242786 c
9 9 4.455582 c
10 10 4.362427 a
> attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)
这依赖于DF$z
是一个因素的事实,因此,当用DF$z
进行子集设置时,其值将被视为整数.因此,颜色矢量的元素将随z
的不同而变化,如下所示:
This relies on the fact that DF$z
is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z
as follows:
> c("red","blue","green")[DF$z]
[1] "green" "blue" "red" "green" "red" "blue" "red" "green" "green" "red"
您可以使用legend
函数添加图例:
You can add a legend using the legend
function:
legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)
这篇关于如何在R中的散点图中为每个类赋予颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!