Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put multiple graphs in one plot with ggvis

Tags:

r

ggvis

Sample data:

y1 = c(1,2,3,4)
y2 = c(6,5,4,3)
x  = c(1,2,3,4)
df = data.frame(x,y1,y2)

My Question:

I would like to combine the following two graphs into one, using ggvis:

df %>% ggvis(~x,~y1) %>% layer_paths()
df %>% ggvis(~x,~y2) %>% layer_paths()

However, the following does not work:

df %>% ggvis(~x,~y1) %>% layer_paths() %>% ggvis(~x,~y2) %>% layer_paths()
like image 824
Alex Avatar asked Jul 25 '14 00:07

Alex


Video Answer


2 Answers

You can refer to the original data and add a layer:

df %>% ggvis(~x,~y1) %>% layer_paths()%>%
  layer_paths(data = df, x = ~x, y = ~y2)

enter image description here

You can remove the reference to the data and it will be inferred:

df %>% ggvis(~x,~y1) %>% layer_paths()%>%
+     layer_paths(x = ~x, y = ~y2)
like image 69
jdharrison Avatar answered Nov 15 '22 05:11

jdharrison


It is possible to merge two ggvis by merging together each of their components:

p1 <- df %>% ggvis(~x,~y1) %>% layer_paths()
p2 <- df %>% ggvis(~x,~y2) %>% layer_paths()

pp <- Map(c, p1, p2) %>% set_attributes(attributes(p1))

I don't know if it works well in all situations, but it works at least for simple plots.

Here is a function that will do it for you:

merge_ggvis <- function(...) {
  vis_list <- list(...)
  out <- do.call(Map, c(list(`c`), vis_list))
  attributes(out) <- attributes(vis_list[[1]])
  out
}

You can use it with objects containing plots:

merge_ggvis(p1, p2)

or in a pipe:

df %>%
  ggvis(~x, ~y1) %>% layer_paths() %>%
  merge_ggvis(
    df %>% ggvis(~x, ~y2) %>% layer_paths()
  )
like image 23
Lionel Henry Avatar answered Nov 15 '22 07:11

Lionel Henry