0

I have a dataframe with 43 versions (columns) of a given process with an unique x-axis (DOY) but for the sake of the example we will suppose I have only 5 versions:

df<-data.frame(DOY = 1:100,replicate(5, runif(100))) 
   DOY           X1          X2          X3         X4          X5
1    1  0.229167049  1.14301363  1.51866596  0.3975288  0.08408749
2    2 -1.201152742  0.78310939  0.73386803  1.0642240  0.08889227
3    3  0.855091117 -0.20336769 -1.43918386 -1.1315914  1.11606984
4    4 -2.503215715 -0.49935691  1.62382889 -2.4111611  2.08002344
5    5  1.060241917 -0.07352165 -0.09702405  0.2453719 -1.49648551
6    6  0.770752629  1.57174443 -1.11631512 -2.0473207  2.69395156
7    7  1.408792920  1.03667735 -0.42335742 -0.2194104 -0.23139360
8    8  0.322702898  0.27546292 -0.29637931 -1.5397543 -0.31331059
9    9 -1.579402811 -0.29110898  0.85435901  0.1051316  0.94311947
10  10 -0.004535567  0.40224405 -0.92110478 -1.2431362  0.46812342

I want to create a ggplot with the following output:

 g[![enter image description here][1]][1]gplot(df, aes(x=DOY)) +
  geom_line(aes(y=X1, color = "A")) + 
  geom_line(aes(y=X2, color = "B")) + 
  geom_line(aes(y=X3, color = "C")) + 
  geom_line(aes(y=X4, color = "D")) +
  geom_line(aes(y=X5, color = "E")) 

enter image description here But due to my high number of columns this approximation its intratable, so im trying to apply melt or gather for a more easy representation, but I can't do it without lost the common x-axis.

My objective is, in first instance, achieve something like this:

enter image description here

To finally obtain an an animation with this effect:

enter image description here

Source: https://robjhyndman.com/hyndsight/ftsviz/

VYago
  • 325
  • 2
  • 9
  • `df %>% gather(col, val, -DOY)`... That will exclude the DOY column from the gathering step, so each series should retain its connection to that variable. – Jon Spring Nov 15 '19 at 21:41
  • this is exactly what I was looking for, if you want, provide an answer and I will resolve the thread. – VYago Nov 15 '19 at 22:17
  • Possible duplicate of [Plotting two variables as lines using ggplot2 on the same graph](https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph) – Jon Spring Nov 15 '19 at 22:23

1 Answers1

0

Have you thought about using plotly?

library(plotly)
p <- plot_ly(df, y=~X1, type="scatter",name= 'X1',mode="lines")
for(i in colnames(df)[3:6]){
    p <- add_trace(p,y = df[[i]], name = i,mode = 'lines')
    print(i)
}
p  
LocoGris
  • 4,432
  • 3
  • 15
  • 30