2012-01-07 84 views
16

如何设置散点图中单个数据点的颜色R设置单个数据点的颜色

我使用plot

+0

是否要绘制所有数据点的特定颜色或只是1个特定的数据点? – jitendra 2012-01-07 23:31:21

+0

我想为散点图中的特定数据点着色。 – nit 2012-01-07 23:45:29

回答

10

使用col=参数,它是矢量使得例如在

plot(1:5, 1:5, col=1:5) 

你在五种不同的颜色得到5分:

enter image description here

你可以使用相同的逻辑来使用两三个您的数据点之间的颜色。了解索引是R的语言中的关键。

28

要扩展@Dirk Eddelbuettel的答案,您可以在plot的调用中使用col的任何函数。举例来说,这个颜色的x==3点红,让所有其他黑色:

x <- 1:5 
plot(x, x, col=ifelse(x==3, "red", "black")) 

example 1

也是一样的性格点pch,性格扩张cex

plot(x, x, col=ifelse(x==3, "red", "black"), 
    pch=ifelse(x==3, 19, 1), cex=ifelse(x==3, 2, 1)) 

example 2

+0

是的,任何_expression_产生一个标量或可循环的向量。所以'col = c(rep(“black”,3),rep(“blue”,2))'会有三个黑点,然后是两个蓝点。 – 2012-01-07 23:53:11

+0

很简单,但我从来没有真正想过在这里使用ifelse。感谢分享+1 – 2012-01-08 04:08:45

17

通过代码做你想做的事很容易,其他rs已经给出了很好的方法来做到这一点。但是,如果您希望点击要更改颜色的点,可以使用'标识'和'点'命令以新颜色重新绘制这些点。

# Make some data 
n <- 15 
x <- rnorm(n) 
y <- rnorm(n) 

# Plot the data 
plot(x,y) 

# This lets you click on the points you want to change 
# the color of. Right click and select "stop" when 
# you have clicked all the points you want 
pnt <- identify(x, y, plot = F) 

# This colors those points red 
points(x[pnt], y[pnt], col = "red") 

# identify beeps when you click. 
# Adding the following line before the 'identify' line will disable that. 
# options(locatorBell = FALSE) 
+0

也很酷的dason。感谢您的分享,也没有想到使用那样的标识。在R Studio中识别也非常容易使用+1 – 2012-01-08 04:13:05

+1

。对于标记点也很好。但不是右键点击“停止” - 在R Studio绘图预览中有一个按钮标记为停止。 – 2012-01-09 05:06:08

+0

@Captain在我的RStudio版本上,它实际上是说“完成” – Dason 2012-01-09 05:14:55