Search code examples
rplotvisualizationggvis

In R, how to draw multiple curves with ggvis?


In R, how to draw multiple curves with ggvis? Not knowing how, I tried to do it with a for loop,

m <- 10
n_max <- 100
n <- seq.int(1, n_max, 1)
s <- matrix(2*(rbinom(n_max*m, size=1, prob=0.5) - 0.5), ncol = m)
x_estimate <- apply(s, 2, function(z) cumsum(z)/seq_along(z))

data <- data.frame(x_estimate, n)
v <- data %>% 
    ggvis(x = ~n, y = ~x_estimate[,c(1)]) %>%
    layer_lines() %>%
    scale_numeric("y", domain = c(-0.5, 0.5), nice = FALSE, clamp = TRUE)
for ( i in 2:m) {
    v <- (v %>% layer_paths(x = ~n, y = ~x_estimate[,c(i)]))
}
v

The resultant plot only has 2 curves instead of m=10 curves. So, somehow the for loop plots overlapping curves. Any ideas? More importantly, how to do this properly with ggvis?


Solution

  • I can't say for sure that's how it should be done, and my solution looks a bit clumsy, but it works.

    v <- data %>% 
      ggvis(x = ~n)
    for (i in 1:m) 
    {
      v <- (v %>% layer_paths(prop("y", as.name(colnames(data)[i]))))
    }
    v %>%
      scale_numeric("y", domain = c(-0.5, 0.5), nice = FALSE, clamp = TRUE, label = 'y')