-1

I have a dataset like this:

T  A B C D
0  1 2 2 4
1  1 4 1 5
2  1 7 2 4 
3  2 9 4 0 
4  2 0 3 0
5  2 3 7 1    
6  1 7 3 5
7  1 7 3 5
8  3 1 6 0
9  3 2 3 9
10  1 2 2 4
11  1 4 1 5
12  1 7 2 4 
13  2 9 4 0 
14  2 0 3 0
15  2 3 7 1 

I want to plot the data in R using ggplot as time series. Here T is the time (x axis). There will be 3 lines for the column B, C and D. I need to highlight the whole plot depending on the values in column A.

For example, if value in A is 1 I don't need to do anything. if value in A is 2 I need to highlight the portion (ex. Time 5-7 and Time 15-16) by a yellow rectangle. if value in A is 3 I need to highlight the portion (ex. Time 10-11) by a blue rectangle.

So the plot should look like a time series plot with several transparent rectangles on it, which will highlight the areas where A has a specific value. I need to add those colors as legend also.

  • 1
    What is your specific question? – Pierre L Mar 10 '16 at 20:30
  • I can plot the time series. I need help about dividing the data according to the values of A column and highlighting the regions. If you look at the A column, there should be 6 segments. I want to highlight the segments with yellow where A==2 and with blue where A==3. – cryptexcode Mar 10 '16 at 20:33
  • Like this http://stackoverflow.com/questions/32543176/highlight-areas-within-certain-x-range-in-ggplot2/32544505#32544505? – Pierre L Mar 10 '16 at 20:34
  • In the link there is only one colour because they had only 2 values. I may need 3/4 colours also. – cryptexcode Mar 10 '16 at 20:40
  • 1
    Still not sure *where* you're stuck. Could you show your code so far? Do you begin by melting your data from wide to long? (You probably should.) – Gregor Thomas Mar 10 '16 at 20:45
  • I am stuck into 2 points. 1. I need to divide the data into segments according to the values in A. So that I can compute the mean of B for each segments. 2. I need to highlight the segments. – cryptexcode Mar 10 '16 at 20:49

1 Answers1

1

Is this what you are trying to do?

library(reshape)
library(ggplot2)
df.mlt <- melt(df, id=c("T","A"))
df.mlt$A <-  as.factor(df.mlt$A)
ggplot(df.mlt, aes(T, value)) +  
geom_ribbon(data=subset(df.mlt, A != 1),aes(x=T,ymax=10,ymin=0, fill=A)) +
geom_line(aes(color=variable)) + scale_fill_manual(values=c("yellow", "blue"))

enter image description here

Wyldsoul
  • 1,468
  • 10
  • 16