在标记中循环时,edgebundle不会渲染绘图

问题描述 投票:0回答:1

我正在尝试创建一个自动报告,我使用edgebundleR创建一系列和弦图。

我有一个功能,可以做一堆东西,或多或少有这种形式:

plot_chords <- function(x,t,pos) {
  ...
  stuff I do with the data
  ...
  g <- graph.adjacency(mydata, mode="upper", weighted=TRUE, diag=FALSE)
  return(edgebundle(g))
}

如果我不在循环中使用它,此函数可以正常工作。如果它像这样循环,它不会:

```{r echo = FALSE,message=FALSE, warning = FALSE,results = "asis"}
for (c in unique(df$Group)) {

  cat("\n\n## ",c," - Negative Correlations (min r=",t_neg," - only significative)\n\n")
  plot_chords(subset(df, Group == c),0.5,0)

}
```

我发现一般情况下,除非我使用print,否则这在循环内部不起作用:

for (c in unique(df$Group)) {
  temp=df[df$Group == c,]
  print(plot_chords(temp,0.5,0))
}

但是打印在降价时不起作用。

我该如何渲染情节?

谢谢。

r knitr r-markdown data-visualization igraph
1个回答
2
投票

edgebundle调用返回一个htmlwidget并且正如你所指出的那样,当你不在循环中时,它会工作。解决您的情况的方法是使用for循环在临时文件中生成几个特定的​​R代码块,然后将该临时文件评估为主.Rmd文件中的子文件。

例如,在.Rmd文件中,这两个块将加载所需的包并定义一个函数foo,它创建并显示一个随机的edgebundle。

```{r}
set.seed(42)
library(edgebundleR)
library(igraph)
```

## test the function

```{r}
foo <- function() {
  adjm <- matrix(sample(0:1, 100, replace = TRUE, prob = c(0.6, 0.4)), nc = 10)
  g <- graph.adjacency(adjm)
  edgebundle(g)
}
```

在块中调用foo两次将在输出.html文档中按预期工作。

```{r}
foo()
foo()
```

要在for循环中生成几个edgebudles,请尝试此操作。编写一个for循环,用所需的R块填充temp.Rmd文件。您需要根据应用程序的需要对其进行修改。

## test the function in a for loop

```{r}
tmpfile <- tempfile(fileext = ".Rmd")
for(i in 1:3) {
  cat("### This is edgebundle", i, "of 3.\n```{r}\nfoo()\n```\n",
      file = tmpfile, append = TRUE) 
}
```

tmpfile的内容如下所示:

### This is edgebundle 1 of 3.
```{r}
foo()
```
### This is edgebundle 2 of 3.
```{r}
foo()
```
### This is edgebundle 3 of 3.
```{r}
foo()
```

要在主输出文件中显示小部件,请使用如下块:

```{r child = tmpfile}
```

完整的.Rmd文件和结果:

example.Rmd:

# edgebundleR and knitr
Answer to https://stackoverflow.com/questions/47926520/edgebundle-doesnt-render-plot-when-in-loop-in-markdown

```{r}
set.seed(42)
library(edgebundleR)
library(igraph)
```

## test the function

```{r}
foo <- function() {
  adjm <- matrix(sample(0:1, 100, replace = TRUE, prob = c(0.6, 0.4)), nc = 10)
  g <- graph.adjacency(adjm)
  edgebundle(g)
}
foo()
foo()
```

## test the function in a for loop

```{r}
tmpfile <- tempfile(fileext = ".Rmd")
for(i in 1:3) {
  cat("### This is edgebundle", i, "of 3.\n```{r}\nfoo()\n```\n",
      file = tmpfile, append = TRUE) 
}
```

```{r child = tmpfile}
```

```{r}
print(sessionInfo(), local = FALSE)
```

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.