简体   繁体   English

如何使用ggvis将多个图形放在一个图中

[英]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 : 我想使用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()

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)

在此输入图像描述

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)

It is possible to merge two ggvis by merging together each of their components: 可以通过将每个组件合并在一起来合并两个ggvis:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM