Search code examples
rggvis

How to put multiple graphs in one plot with 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()

Solution

  • 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)