R DiagrammeR包-动态更新图表

R DiagrammeR包-动态更新图表,r,diagrammer,R,Diagrammer,我试图在for循环的每个步骤中更新R Studio查看器中的图表 在循环结束时,我希望获得以下信息: 但我得到的是: 上面的代码如下所示: library(tidyverse) library(DiagrammeR) a_graph <- create_graph() %>% add_node(label = 'Start', type = 'actif', node_aes = node_aes(fillcolor = "orange",shape = "rectan

我试图在for循环的每个步骤中更新R Studio查看器中的图表

在循环结束时,我希望获得以下信息:

但我得到的是:

上面的代码如下所示:

library(tidyverse)
library(DiagrammeR)

a_graph <-
  create_graph() %>%
  add_node(label = 'Start', type = 'actif', node_aes = node_aes(fillcolor = "orange",shape = "rectangle"
  ) ) 

a_graph %>% render_graph()


update_my_graph <- function(label, label_from){
  from_id <- which( (a_graph %>% get_node_df())$label==label_from )
  a_graph <<- a_graph %>% 
    select_nodes(
      conditions = 
        type == 'actif') %>%
    set_node_attrs_ws(
      node_attr = fillcolor,
      value = "blue") %>%
    clear_selection() %>% 
    add_node(label = label, from = from_id, type = 'actif', node_aes = node_aes(fillcolor = "orange",shape = "rectangle",fixedsize = FALSE))
  a_graph %>% render_graph(layout = "tree")
}

for(i in 1:5) update_my_graph(i,'Start')
库(tidyverse)
图书馆(图解机)
a_图%
添加节点(标签='Start',类型='actif',节点=节点
) ) 
_图%>%render_图()
更新我的图表%
清除所选内容()%>%
添加节点(label=label,from=from\u id,type='actif',node\u aes=node\u aes(fillcolor=“orange”,shape=“rectangle”,fixedsize=FALSE))
图%>%呈现图(layout=“tree”)
}
对于(1:5中的i)更新我的图(i,'Start')
R版本3.4.1(2017-06-30)-“单根蜡烛” tidyverse 1.2.1 图表1.0.0
RStudio 1.1.383

您的功能确实正确。“坏结果”实际上是第7行中的第一个
a_-graph%>%render_-graph()
,并且没有调用进一步的绘图,因此得到了结果。要看到这一点,您可以在执行(1:5中的i)更新\u我的图(i,'Start')之前删除绘图。您将看到没有打印输出。在完成五次更新后,您可以再次调用
a_-graph%>%render_-graph(layout=“tree”)
,您将看到它已经为您提供了所需的结果。函数本身不打印绘图

因此,简单的做法如下:

update_my_graph <- function(label, label_from){
  from_id <- which((a_graph %>% get_node_df())$label==label_from)
  a_graph <<- a_graph %>% 
    select_nodes(conditions = type == 'actif') %>%
    set_node_attrs_ws(node_attr = fillcolor, value = "blue") %>%
    clear_selection() %>% 
    add_node(label = label, from = from_id, type = 'actif', 
             node_aes = node_aes(fillcolor = "orange", 
                                 shape = "rectangle", 
                                 fixedsize = FALSE))
  print(a_graph %>% render_graph(layout = "tree"))
}
更新我的图表%
清除所选内容()%>%
添加节点(label=label,from=from\u id,type='actif',
node_aes=node_aes(fillcolor=“orange”,
shape=“矩形”,
fixedsize=FALSE)
打印(图形%>%渲染图形(layout=“tree”))
}
也就是说,只需在
a\u graph%>%render\u graph(layout=“tree”)
周围放置
print
。您还可以执行
返回(a_-graph%>%render_-graph(layout=“tree”))
然后调用存储的绘图