簡體   English   中英

R DiagrammeR軟件包-動態更新圖表

[英]R DiagrammeR package - Dynamically update diagram

我試圖在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')

R版本3.4.1(2017-06-30)-“ Single Candle” tidyverse 1.2.1 DiagrammeR 1.0.0 RStudio 1.1.383

您的功能確實正確。 “不良結果”實際上是您在第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"))然后調用存儲的圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM