1

I have an RMarkdown document where I use data.tree and DiagrammeR to generate models. I then display these using a set-up similar to the one used in How to include DiagrammeR/mermaid flowchart in a Rmarkdown file

For example:

```{r fig.cap="Structureel model bij enkelvoudige regressie.", fig.with=4, fig.height=1}

drawStructuralModel <- function(covariates, criterion) {
  ### Create tree
  res <- Node$new(criterion);
  for (covariate in covariates) {
    res$AddChild(covariate);
  }
  ### Set display settings
  SetEdgeStyle(res, dir='back');
  res <- ToDiagrammeRGraph(res, direction = "descend");
  res <- add_global_graph_attrs(res, "layout", "dot", "graph");
  res <- add_global_graph_attrs(res, "rankdir", "RL", "graph");

  ### Draw and return tree
  render_graph(res);
}

drawStructuralModel("X", "Y");

```

So far so good. The caption text is added, which is what you'd expect.

Except :-)

Above, in the 'setup' knitr chunk, I used setFigCapNumbering from userfriendlyscience (see https://github.com/Matherion/userfriendlyscience/blob/master/R/setFigCapNumbering.R). This function uses knit_hooks$set to set a hook for plots, so that the captions are automatically numbered.

But this numbering isn't applied to the DiagrammeR output.

I guess that makes sense, since it's not actually a plot, rather an HTML widget or some SVG or so. I would still like it to be numbered as a figure, though.

But how do I find out which hook knitr invokes when DiagrammeR output is generated?

I could always resort to using the more generic 'automatic caption' function setCaptionNumbering (https://github.com/Matherion/userfriendlyscience/blob/master/R/setCaptionNumbering.R), and tell it to use the same counter option as the figure caption thingy uses. That would sidestep the issue, but I'd prefer to modify the appropriate knitr hook.

And since this problem (figuring out which hook knitr uses for output produced by a given function) probably occurs more often, I thought it would be worth opening an SA question.

Does anybody know how you can find this out?

4

1 回答 1

2

knitr调用knit_print给定块产生的输出。然后根据输出的类调用适当的方法。您可以通过运行找出可用的方法methods("knit_print"),然后查看是否有任何方法与 DiagrammeR 的输出类匹配。

看看你的例子,我猜你的输出类是"DiagrammeR" "htmlwidget",所以 knitr 正在调用knit_print.htmlwidget

深入研究该源代码,它调用htmltools::knit_print.html包装标签,然后输出 asis。因此,为了回答您的问题,它使用默认挂钩以您使用的任何输出格式进行 asis 输出。

于 2017-05-17T14:58:28.547 回答