Search code examples
rplotprogram-entry-pointtitle

Why is there main and title?


There are two different options (main within the plot and title afterwards, which calls main again) to add an header to the plot. I want to know what is the difference between these two. Which one shall I use?

The code below gives a minimal example and produces the graphs.

library(mvtnorm)
par(mfrow=c(2,1))
x = rmvnorm(10,c(2,2),matrix(c(2,0,0,2),2))
plot(x, main='title')
plot(x)
title(main='title')

<code>Title</code> and <code>main</code> used for two graphs.

Thanks for your help.


Solution

  • They are identical except that title allows you to add a title after making the plot, as opposed to defining it atomically. Use whichever is most convenient. If you have a lot of arguments specified within plot, you might like to specify the title on a separate line to make your code more readable, for example.

    To see that they are equivalent, look at the definition of plot.default() in your console. The very last line is an indirect call to title() where main and sub are passed through:

    > plot.default
    function (x, y = NULL, type = "p", xlim = NULL, ylim = NULL, 
        log = "", main = NULL, sub = NULL, xlab = NULL, ylab = NULL, 
        ann = par("ann"), axes = TRUE, frame.plot = axes, panel.first = NULL, 
        panel.last = NULL, asp = NA, ...) 
    {
    
        # [code left out for clarity]
    
        localTitle <- function(..., col, bg, pch, cex, lty, lwd) title(...)
    
        # [code left out for clarity]
    
        if (ann) 
            localTitle(main = main, sub = sub, xlab = xlab, ylab = ylab, 
                ...)
        invisible()
    }