R DiagrammeR 包 - 动态更新图表

R DiagrammeR package - Dynamically update diagram

我正在尝试在 for 循环的每一步更新 R Studio 查看器中的图表。

在循环结束时我想得到这个:

wish result

但是我得到了这个:

bad result

上面的代码是这样的:

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

R 版本 3.4.1 (2017-06-30) -- "Single Candle" 整洁宇宙 1.2.1 DiagrammeR 1.0.0 RStudio 1.1.383

你的功能是正确的,真的。 "bad result" 实际上是您在第 7 行中的第一个 a_graph %>% render_graph() 并且没有调用进一步的图,因此结果。要看到这一点,您可以在 您经历 for(i in 1:5) update_my_graph(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"))
}

也就是说,只需将 print 放在 a_graph %>% render_graph(layout = "tree") 的周围。您也可以执行 return(a_graph %>% render_graph(layout = "tree")) 然后调用存储的绘图。