plot(x,y,col =)在R中工作错误?

时间:2014-07-04 21:10:38

标签: r plot

我在理解情节中col参数的工作原理时遇到了问题。

我们先来看看这个:

plot(collection[,"x"], collection[,"y"], 
     col=rainbow(21300)[order(collection[,"y"])],pch=".")

enter image description here

颜色几乎与y轴对齐,但是并非完全。

现在让我们这样做:

plot(collection[,"x"], collection[,"y"],
    col=rainbow(21300)[order(collection[,"x"])],pch=".")

我希望颜色从左到右渐变,因为我在与表示x轴的数据相同的数据上对它们进行了排序。

但不,这是一个完整的混乱。

那它是如何运作的?

enter image description here

1 个答案:

答案 0 :(得分:7)

也许您的数据已经按y值(或接近的值)排序。 col=参数为您按照点出现的顺序绘制的每个点指定颜色。执行order()时,您将返回属于每个位置的元素的索引。如果您的数据已经排序,这与当前位置不会有太大差异。但如果不是,那就是你如何重新排序它。这不是值本身落入的序列。您可能应该使用order()而不是rank()。这给出了每个元素的就地顺序。

这里有一些示例数据

y<-cumsum(runif(1000, -.5, 1))
x<-sin(seq(1:length(y))/7+rnorm(length(y),.5,.1))

你会看到

plot(x,y, col=rainbow(length(y))[order(y)], main="order y")
plot(x,y, col=rainbow(length(y))[order(x)], main="order x")

enter image description here

y的顺序看起来不错,因为数据基本上是以y开头的顺序。 x看起来很疯狂,因为当您按x排序颜色时,您不是通过x自己排序x值。你可以做到

plot(x,y, col=rainbow(length(y))[rank(y)], main="rank y")
plot(x,y, col=rainbow(length(y))[rank(x)], main="rank x")

enter image description here

获得更像你期待的情节。或者,您也可以订购数据

plot(x[order(y)],y[order(y)], col=rainbow(length(y)), main="data y")
plot(x[order(x)],y[order(x)], col=rainbow(length(y)), main="data x")

enter image description here