2016-05-30 117 views
2

我有這個情節,我需要從觀察2,000向前改變線的顏色爲紅色。我已經使用ggplot完成了它,這很容易,但我想用Base R來完成。我一直在閱讀一些帖子,但我還沒有弄清楚我該怎麼做。更改給定日期的顏色?

所以這就是它,一部分情節是藍色的,另一部分是紅色的。

我真的很感激任何建議或建議! Plot

回答

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) 

正如你說,「H」的功能是不恰當的工具,也可以用一個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

+0

謝謝你,這個工作如果我使用直方圖選項。我正在使用行選項。它是使用移動應用程序發送的消息每小時數據的調整時間序列(我不能發佈數據)。所以我想這與直方圖和線路完全不一樣。 – adrian1121

+0

@ adrian1121嘗試構建一個類似於您的數據集或交換值。我認爲顏色不適用於使用「l」選項的矢量。我編輯了我的答案。 – Jimbou

0

更改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")) 

plot

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

相關問題