对于n对坐标x的列表,y是否有一种方法可以绘制特定颜色上不同点之间的直线?
我到目前为止所实现的解决方案是不使用情节功能,但行选择了我想要的颜色范围.这是一个例子:
x <- 1:100
y <- rnorm(100,1,100)
plot(x,y ,type='n')
lines(x[1:50],y[1:50], col='red')
lines(x[50:60],y[50:60], col='black')
lines(x[60:100],y[60:100], col='red')
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?
是的,这样做的一种方法是使用ggplot.
ggplot要求您的数据采用data.frame格式.在此data.frame我添加一个col表示您所需颜色的列.然后使用ggplot,, 构建绘图geom_line,scale_colour_identity因为col变量已经是颜色:
library(ggplot2)
df <- data.frame(
x = 1:100,
y = rnorm(100,1,100),
col = c(rep("red", 50), rep("black", 10), rep("red", 40))
)
ggplot(df, aes(x=x, y=y)) +
geom_line(aes(colour=col, group=1)) +
scale_colour_identity()
Run Code Online (Sandbox Code Playgroud)

更一般地,每个线段可以是不同的颜色.在下一个例子中,我将颜色映射到x值,给出了一个平滑地将颜色从蓝色变为红色的图:
df <- data.frame(
x = 1:100,
y = rnorm(100,1,100)
)
ggplot(df, aes(x=x, y=y)) + geom_line(aes(colour=x))
Run Code Online (Sandbox Code Playgroud)

如果你坚持使用基本图形,那么使用segments如下:
df <- data.frame(
x = 1:100,
y = rnorm(100,1,100),
col = c(rep("red", 50), rep("black", 10), rep("red", 40))
)
plot(df$x, df$y, type="n")
for(i in 1:(length(df$x)-1)){
segments(df$x[i], df$y[i], df$x[i+1], df$y[i+1], col=df$col[i])
}
Run Code Online (Sandbox Code Playgroud)
