[英]R DiagrammeR package - Dynamically update diagram
I am trying to update a diagram in R Studio viewer at each step of a for loop. 我试图在for循环的每个步骤中在R Studio查看器中更新一个图。
At the end of the loop I would like to obtain this: 在循环结束时,我想获得以下内容:
But I obtain this: 但是我得到这个:
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 R版本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. “不良结果”实际上是您在第7行中的第一个
a_graph %>% render_graph()
,并且没有进一步的绘图被调用,因此是结果。 To see this, you can erase the plot before you undergo for(i in 1:5) update_my_graph(i,'Start')
. 要看到这一点,可以在进行
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. 完成五次更新后,您可以再次调用
a_graph %>% render_graph(layout = "tree")
,您会看到它已经为您提供了想要的结果。 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")
. 也就是说,只需将
print
放在a_graph %>% render_graph(layout = "tree")
周围。 You could also do return(a_graph %>% render_graph(layout = "tree"))
then call the stored plot. 您也可以
return(a_graph %>% render_graph(layout = "tree"))
然后调用存储的图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.