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?

Matherion
  • 657
  • 1
  • 5
  • 13

1 Answers1

2

knitr calls knit_print on the output produced by a given chunk. This then calls the appropriate method based on the class of the output. You can find out what methods are available by running methods("knit_print"), then see if any of those match the class of the output from DiagrammeR.

Looking at your example, I'm guessing the class of your output is "DiagrammeR" "htmlwidget", so knitr is calling knit_print.htmlwidget.

Digging into that source code, it calls htmltools::knit_print.html, which wraps the tags and then outputs asis. So to answer your question, it uses the default hooks for asis output in whatever output format you're using.

tmpname12345
  • 2,891
  • 18
  • 20