简体   繁体   中英

R DiagrammeR package - Dynamically update diagram

I am trying to update a diagram in R Studio viewer at each step of a for loop.

At the end of the loop I would like to obtain this:

wish result

But I obtain this:

bad result

The code for the above is like this:

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 version 3.4.1 (2017-06-30) -- "Single Candle" tidyverse 1.2.1 DiagrammeR 1.0.0 RStudio 1.1.383

Your function is correct, really. The "bad result" is actually your first a_graph %>% render_graph() in line 7 and no further plots have been called, hence the result. To see this, you can erase the plot before you undergo for(i in 1:5) update_my_graph(i,'Start') . You will see that there is no plot output. And after you have done the five updates, you can again call a_graph %>% render_graph(layout = "tree") and you will see that it has given you the result that you wanted. The function itself is not printing the plot.

Hence it is a simple matter to do as follows:

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"))
}

That is, simply put print around the a_graph %>% render_graph(layout = "tree") . You could also do return(a_graph %>% render_graph(layout = "tree")) then call the stored plot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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