Search code examples
rloopsplotggvis

Multiple line graphs in ggvis using for loop


I am trying to create multiple line graphs using ggvis. I am able to plot multiple lines but I am unable to add tooltip for these lines. I need to show the x and y value when I hover the mouse on the lines. I also am unable to add points to the lines in the for loop.

Below is a simplified example I am working with. column "c1" is the x values and columns "c2", "c3" and "c4" are to be plotted(lines with points and tooltip) Screenshot of the plot

mydf <- data.frame(c(1:10),c(11:20), c(21:30), c(31:40))
v <- c("c1","c2","c3", "c4")
names(mydf) <- v
myggv <- mydf %>% ggvis(x = ~c1, y = ~c2) %>% layer_lines() %>% layer_points() %>% add_tooltip( function(mydf){paste0("x:",mydf$c1,"<br>","y:",mydf$c2)}, "hover")
for(r in v[2:length(v)]){
myggv <- (myggv  %>% layer_paths(x = ~c1, y = as.name(r)) %>% layer_points()
%>% add_tooltip( function(mydf){paste0("x:",mydf$c1,"<br>","y:",mydf[,r] )}, "hover"))
}

Thanks


Solution

  • The best approach here is to not use a for loop. I mean, you can, but it's not the way ggvis approaches things. Also I can't get the tooltip to work in the loop (it gives the only the correct result for the last added line. But here is how I would do it anway:

    mydf <- data.frame(c1 = c(1:10),
                       c2 = c(11:20), 
                       c3 = c(21:30), 
                       c4 = c(31:40))
    myggv <- ggvis(mydf)
    for (r in names(mydf)[-1]) {
      myggv <- (myggv  %>% 
                  layer_paths(x = ~c1, y = as.name(r)) %>% 
                  layer_points(x = ~c1, y = as.name(r)) %>% 
                  add_tooltip(function(mydf) { 
                    paste0("x:", mydf[[1]], "<br>", "y:", mydf[[r]])}, "hover"))
    }
    

    The nicer way is to restructure your data, and then use group_by to create seperate lines. As an added benefit, this is perhaps nicer to read. This way your tooltips also work:

    mydf2 <- tidyr::gather(mydf, 'var', 'val', -c1)
    
    myggv2 <- mydf2 %>% 
      ggvis(x = ~c1, y = ~val) %>% 
      layer_points() %>% 
      add_tooltip(function(d) { paste0("x:", d$c1, "<br>", "y:", d$val) }, "hover") %>% 
      group_by(var) %>% 
      layer_paths()
    

    You might want to use layer_lines() instead of layer_paths().

    enter image description here