从给定日期改变颜色?

时间:2016-05-30 15:15:44

标签: r plot base

我有这个情节,我需要将线条的颜色从观察2,000改为红色。我使用ggplot完成它并且它很容易但我想使用Base R来做它。我一直在阅读一些帖子但我还没弄清楚我应该怎么做。

所以就是这样,部分情节为蓝色,另一部分为红色。

我真的很感激任何建议或推荐!  Plot

3 个答案:

答案 0 :(得分:0)

您没有提供数据,所以我只能假设。这里是使用基本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)

正如你所说&#34; h&#34;功能不是一个合适的工具,您也可以使用looplines

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])
}

enter image description here

答案 1 :(得分:0)

更改line()颜色是一件麻烦的事,我使用了segment()来制作重复的端点数据。

# 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"))

plot

答案 2 :(得分:0)

试试这个:

df <- data.frame(ind = 1:5000, y = runif(5000, 0, 10))


plot(df$y, type="h", col= ifelse( df$ind < 2000, "blue", "red"))

enter image description here