Neural Net Plot not showing up on the HTML rendered from a R Markdown

Hi @Rolodex! Welcome!

I'm assuming you are using the neuralnet package here — it's really helpful if you can at least include sample code with library() calls in questions like this, since there are a lot of packages out there and many of them have similarly named functions! :sweat_smile: Even better is a self-contained reproducible example.

It seems like the plot.nn method in the neuralnet package was not written with non-interactive use in mind, so it doesn't entirely play nicely with how knitr captures plot output.

I suspect that the root of the problem is this bit, from the plot.nn documentation:

rep repetition of the neural network. If rep="best", the repetition with the smallest error will be plotted. If not stated all repetitions will be plotted, each in a separate window.

knitr runs all of your code in a non-interactive session, where calls such as (which plot.nn uses when nothing is supplied to rep) are both unnecessary and will not work.

If you just want the single plot with the smallest error, then specifying rep = "best" seems to help, as in this sample R Markdown document:

title: "`neuralnet` + R Markdown"
output: html_document

nn <- neuralnet(Species ~ Petal.Length + Petal.Width, iris, linear.output = FALSE)

This code block won't have any captured plot output:


Supplying `"best"` to `rep` results in a single plot being captured:

plot(nn, rep = "best")

Which knits to:

(By the way, this is one example of how one might go about creating a self-contained, reproducible example for this question :grin:. For the model object line, I just used one of the examples from the neuralnet documentation.)

If you need to include more than just the "best" repetition, I think you'll need to save the plot outputs to file using the file argument to plot.nn and then include the images with knitr::include_graphics().

You might also consider submitting a feature request to the GitHub issue tracker for neuralnet to see if the developer is interested in implementing better support for plotting inside R Markdown documents.