I am sure this is an easy question but I found only difficult answers... I just started to do some R programming and I really like the dplyr and ggvis package.. However I could not figure out how to combine multiple line graphs in one diagram. I measured different samples over time and my data looks something like this:
time <-1:10
m = matrix(c(2, 4, 3, 1, 5, 7),nrow=10,ncol=3,byrow = FALSE)
colnames(m)<-c("sample1","sample2","sample3")
mdata <- data.frame(time, m)
data <-tbl_df(data)
I know that it works to chain the layers together but that would not be handy for my data set which contains MANY samples....
data %>% ggvis() %>% layer_paths(~time,~sample1) %>% layer_paths(~time,~sample2)%>%layer_paths(~time, ~sample3)
Any suggestions to make this work with ggvis? I played around with a for loop but without success.. Thank you very much!
Your issue here is, that your data needs to be in long format instead of wide format for ggvis
to be able to plot it. You can use tidyr
to do the reshaping. For further reference I recommend you this cheatsheet about restructuring data.
library(ggvis)
library(tidyr)
library(dplyr)
time <- 1:10
m <- matrix(c(2, 4, 3, 1, 5, 7), nrow = 10, ncol = 3, byrow = FALSE)
colnames(m) <- c("sample1", "sample2", "sample3")
mdata <- data.frame(time, m)
data <- tbl_df(mdata)
# gather your data into long format
data <- data %>%
gather(sample, value, -time)
data %>%
ggvis(~time, ~value, stroke = ~sample) %>%
layer_lines()