0

I have some problems by looping "geom_line" functions.

I have this code, that Works ok for me.

variables<-c("irritabilidad","duracionsuenho")
ggplot(dfu) + 
geom_line(data = dfu, aes(x = dfu[,c("fecha")], y = dfu[,c(variables[1])],color = "1") ) + 
geom_line(data = dfu, aes(x = dfu[,c("fecha")], y = dfu[,c(variables[2])],color = "2") ) +

scale_color_manual(name="Legenda",values=rainbow(length(variables)),labels=variables) +
xlab('Fecha') +
ylab('Variables')     

The result :

enter image description here

Now, Im trying to add "geom_line" by looping all the variables:

variables<-input$variables

variables<-c("irritabilidad","duracionsuenho")
c<-0    
p<-ggplot(dfu)

for (x in variables){        
    c<-c+1
    p<-p+geom_line(data = dfu, aes(x = dfu[,c("fecha")], y = dfu[,c(x)],color = as.character(c)) )
}

p<-p+scale_color_manual(name="Variables",values=rainbow(length(variables)),labels=variables) 
p<-p+xlab('Fecha') 
p<-p+ylab('Variables')             
p

And this is the result:

enter image description here

I need to loop because i have several variables. Can you tell me what is wrong? Many Thanks

Lev
  • 693
  • 1
  • 8
  • 24
  • Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Mar 31 '19 at 17:33
  • 1
    This is a ggplot2 anti-pattern. https://stackoverflow.com/a/980616/6851825 You will get much more reliable behavior from ggplot2, with much less work, if you convert your data first to "tidy" form, where the name of each series goes into a single column, which you then map to an aesthetic (like color). https://r4ds.had.co.nz/tidy-data.html – Jon Spring Mar 31 '19 at 17:51

0 Answers0