根据值绘制带条件颜色的折线图

Seb*_*ian 11 plot r

我想绘制折线图.根据值,它应该改变它的颜色.我发现的是:

plot(sin(seq(from=1, to=10,by=0.1)),type="p", 
       col=ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","yellow"))
Run Code Online (Sandbox Code Playgroud)

这样可行.但是一旦我从type ="p"变为type ="l",条件着色就会消失.

这种行为有意吗?

什么是基础图形的解决方案,以绘制具有不同颜色的功能线?

And*_*rie 16

segments而不是lines.

segments功能仅添加到现有绘图中.要创建具有正确的轴和限制的空白地块,首次使用plottype="n"画"无".

x0 <- seq(1, 10, 0.1)
colour <- ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","blue")

plot(x0, sin(x0), type="n")
segments(x0=x0, y0=sin(x0), x1=x0+0.1, y1=sin(x0+0.1), col=colour)
Run Code Online (Sandbox Code Playgroud)

有关?segments详细信息,请参阅

在此输入图像描述


Gre*_*now 9

这是一个有点不同的方法:

x <- seq(from=1, to=10, by=0.1)
plot(x,sin(x), col='red', type='l')
clip(1,10,-1,.5)
lines(x,sin(x), col='yellow', type='l')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请注意,使用此方法时,曲线会将颜色精确地改为0.5.