Why is R inconsistent with the add
parameter in the plot()
function?
It sometimes works and sometimes doesn't!
In this example, it takes the parameter add=TRUE
with no problem:
plot(0:10, 0:10*3)
plot(identity, add=TRUE, xlim=c(0,10))
plot(function (x) { sin(x)*10 }, add=TRUE, xlim=c(0,10))
But when I issue
plot(c(2, 3, 4), c(20,10,15), add=TRUE, pch="A")
It doesn't work!! It says that "add" is not a graphical parameter.
Please do not write that I should use points()
instead. I know I can use it.
I want to understand the strange behaviour of R - why does it sometimes work and sometimes not?
This is admittedly annoying and inconsistent, but it's explicable.
edit: the fact that
identity
is a built-in object (identity function) eluded me (so the problem is in fact reproducible).identity
is an object of a class --function
-- that has aplot
method (plot.function
) with anadd
argument, while the defaultplot
method does not have anadd
argument.In general, when trying to plot object
bar
, you should tryclass(bar)
; if it is of classfoo
then trymethods(class="foo")
to see that it has a plot method, ormethods("plot")
to see thatplot.foo
exists. Try?plot.foo
to see help, orplot.foo
orgetAnywhere(plot.foo)
to see the function itself.This is because when you call
plot(0:10, 0:10*3)
orplot(c(2, 3, 4), c(20,10,15))
, you are indirectly callingplot.default()
, which in turn callsplot.xy()
, whereas the other two calls you mention are runningplot.function()
.add
is an argument forplot.function()
, but not forplot.xy()
.You can get around this inconsistency by setting
par(new = TRUE)
, but then you need to make sure that you don't add fresh axis labels or redraw the axes. EDIT: As pointed out in the comment, you have to make sure that the range is the same as the previous plot. e.g.:As Ben Bolker mentions,
methods('plot')
will show you what methods can be called when runningplot()
- the different methods have different arguments, which are listed when you callargs(plot.foo)
or in the help page?plot.foo