【发布时间】:2016-09-28 11:32:24
【问题描述】:
我有这个情节,我需要将线的颜色从观察 2,000 起更改为红色。我已经使用 ggplot 完成了它,这很容易,但我想使用 Base R 来完成。我一直在阅读一些帖子,但我还没有弄清楚我应该如何做到这一点。
就是这样,部分情节为蓝色,另一部分为红色。
【问题讨论】:
我有这个情节,我需要将线的颜色从观察 2,000 起更改为红色。我已经使用 ggplot 完成了它,这很容易,但我想使用 Base R 来完成。我一直在阅读一些帖子,但我还没有弄清楚我应该如何做到这一点。
就是这样,部分情节为蓝色,另一部分为红色。
【问题讨论】:
更改lines() 颜色有点麻烦,我使用segments() 制作重复的端点数据。
# make a sample data
df <- data.frame(ind = 1:200, y = runif(200, 0, 10))
# combine df and df shifting one row
df <- cbind(df, rbind(df, c(NA, NA))[-1,])
plot(df[,1:2], type="n") # (edit) using Mr.Pereira's code, thanks.
segments(df[,1], df[,2], df[,3], df[,4], col = ifelse( df[,1] < 150, "blue", "red"))
【讨论】:
您没有提供任何数据,所以我只能假设。这里使用基本 R plot 函数的解决方案:
# some data
set.seed(123)
d <-runif(3000, 0, 2)
d[sample(1:3000, 2800)] <- 0 # set some zero values
# A color vector
COL <- c(rep(1, 2000), rep(2, length(d)))
# and the plot using the histogram option:
plot(d, type="h", col=COL)
正如你所说的“h”函数不是一个合适的工具,你也可以使用loop和lines:
plot(d, type="n")
for(i in 1:length(d)){
M <- cbind(c(i, i), c(d[i], 0)) # Matrix of start and end points of the line
lines(M, col=COL[i])
}
【讨论】: