R inconsistency: why add=T sometimes works and sometimes not in the plot() function?

后端 未结 2 1332
无人共我
无人共我 2020-12-24 00:30

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 param

相关标签:
2条回答
  • 2020-12-24 01:21

    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 a plot method (plot.function) with an add argument, while the default plot method does not have an add argument.

    In general, when trying to plot object bar, you should try class(bar); if it is of class foo then try methods(class="foo") to see that it has a plot method, or methods("plot") to see that plot.foo exists. Try ?plot.foo to see help, or plot.foo or getAnywhere(plot.foo) to see the function itself.

    0 讨论(0)
  • 2020-12-24 01:25

    This is because when you call plot(0:10, 0:10*3) or plot(c(2, 3, 4), c(20,10,15)), you are indirectly calling plot.default(), which in turn calls plot.xy(), whereas the other two calls you mention are running plot.function(). add is an argument for plot.function(), but not for plot.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.:

    plot(0:10, 0:10*3)
    plot(identity, add=T, xlim=c(0,10))
    plot(function (x) { sin(x)*10 }, add=T, xlim=c(0,10))
    par(new = TRUE)
    plot(c(2, 3, 4), c(20,10,15), pch="A",
         axes = FALSE, ## don't redraw the axes 
         xlab = '', ylab = '', ## no fresh axis labels
         xlim = c(0,10), ylim = c(0,30)) ## keep the same limits as before
    

    As Ben Bolker mentions, methods('plot') will show you what methods can be called when running plot() - the different methods have different arguments, which are listed when you call args(plot.foo) or in the help page ?plot.foo

    0 讨论(0)
提交回复
热议问题