Andreas
Andreas

Reputation: 85

Giving colors to line plot in R

I have the following matrix (defined as cashflow) that I want to plot in a line plot.

     [,1]       [,2]    [,3]    [,4]    [,5]   
 [1,] 2498237  3018931.0 3351470 3369931 3361170 
 [2,] 2498237  2996003.7 3238663 3330045 3355259 
 [3,] 2498237  2984259.1 3055009 3290842 3280611 
 [4,] 2498237  2951007.4 3034455 3272052 3271609 
 [5,] 2498237  2854107.7 2927473 3180767 3264394 
 [6,] 2498237  2831014.7 2898604 3066758 3229430 
 [7,] 2498237  2817957.7 2897599 3028093 3171877 
 [8,] 2498237  2802613.5 2897572 2988316 3065650 
 [9,] 2498237  2761771.7 2885572 2985963 3059341 
[10,] 2498237  2753574.5 2841593 2822220 2877972 

I want to give colors to each row. However, I want rows >= row[6,] to have the same color (ex. red), rows between row[6] and row[3,] to have the same color (ex. blue), and rows =< row[3,] to have the same color (ex. green).

How may I implement this into the r-code below?

plot(timeline,casflow[1,], ylim=range(2000000,5000000), type ="l")
for (i in 1:total.simulations){
lines(timeline,cashflow[i,])}

Thanks!

Upvotes: 1

Views: 158

Answers (2)

Cath
Cath

Reputation: 24074

I don't have your timeline vector but here is what you can do, using matplot to avoid the loop:

matplot(t(cashflow), type="l", col=c(rep("green",3),rep("blue",2), rep("red",nrow(cashflow)-6+1)))

enter image description here

EDIT

If you have nr numbers numbers of row (nr <- nrows(cashflow)) and you want the 10% (let assume nr, the number of simulations, can be divided by 10) first rows in green and the 10% last rows in red, the other rows in blue, you can do:

First, create your vector of colours:

vec_col <- c(rep("green", nr*0.1), rep("blue", nr*0.8), rep("red", nr*0.1))

Then plot the lines:

matplot(t(cashflow), type="l", col=vec_col)

Upvotes: 1

Roman
Roman

Reputation: 17648

use if in your loop and a color vector

plot(timeline,casflow[1,], ylim=range(2000000,5000000), type ="l")
COL <- c("red","blue","green")
for (i in 1:total.simulations){
if(i <= 3) { z <- 3  }
if(i >= 6) { z <- 1  }
if(i > 3 & i < 6 ) { z <- 3  }
lines(timeline,cashflow[i,], col=COL[z])}

Upvotes: 0

Related Questions