1

Following this example, I would like to add a title to the plot. I use the package neuralnet in R and when the neural network is trained, I want to display in a plot.

library(neuralnet)
data(infert, package="datasets")
net.infert <- neuralnet(case~parity+induced+spontaneous, infert, 
                    err.fct="ce", linear.output=FALSE, likelihood=TRUE)

plot(net.infert, rep="best")

In order to include a title I used the arguments main and title with no result.

plot(net.infert, rep="best", title = "Incisors")

plot(net.infert, rep="best", main= "Incisors")

Any idea?

antecessor
  • 2,688
  • 6
  • 29
  • 61
  • Does `plot(..., title = "Incisors", ann = TRUE)` help? `ann` for annotation *might* be set to `FALSE` by the one or other higher plotting function (see `?par`). – I_O Dec 27 '22 at 23:01
  • Nope, it does not work... Any other idea? – antecessor Dec 28 '22 at 06:08

2 Answers2

2

Looking at its plot.nn method, this neuralnet plot is underpinned by the grid package. You could use grid::grid.text to place an annotation to serve as a title, kinda like this:

plot(net.infert, rep="best")
grid::grid.text("My title", x=0.15, y=0.95, 
                gp=gpar(fontsize=20, col = "darkred"), check=TRUE)
xilliam
  • 2,074
  • 2
  • 15
  • 27
2

extending @xilliam 's solution to position the title above the plot panel:

library(grid)
library(gridExtra)

plot(net.infert, rep="best")

## grab the current output:
plot_panel <- grid.grab(wrap = TRUE)

## create a title grob:
plot_title <- textGrob("A title, a kingdom for a title!",
                       x = .5, y = .1, ## between 0 and 1, from bottom left
                       gp = gpar(lineheight = 2, ## see ?gpar
                                 fontsize = 18, col = 'red',
                                 adj = c(1, 0)
                                 ) 
)

##stack title and main panel, and plot:
grid.arrange(
  grobs = list(plot_title,
               plot_panel),
  heights = unit(c(.15, .85), units = "npc"), ## between 0 and 1
  width = unit(1, "npc")
)

output

I_O
  • 4,983
  • 2
  • 2
  • 15