`plot` 如何知道如何在没有进一步说明的情况下绘制对象?

How does `plot` know how to plot an object without further specification?

使用 R 基函数 plot 我们可以通过提供数据来绘制不同的图,而无需指定进一步的参数。例如,如果我们绘制一个时间序列,使用 plot(my_ts) 调用 plot.ts(my_ts) 因为 my_ts 是 class ts.

同样,我们可以不带任何参数地使用 plot ANOVA 结果。这里有一些方差分析模型:

data <- data.frame(group = c(rep("group_1",25),rep("group_2",25)), scores = c(runif(25,0,1),runif(25,1.5,2.5)))
mod1 <- aov(scores~group,data=data)

使用 plot(mod1) 有效,但 plot(summary(mod1)) 导致错误

"Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' is a list, but does not have components 'x' and 'y'".

似乎 plot 函数在尝试自动创建不带任何参数的绘图时查找名为 xy 的数据。我尝试了 names(mod1),但找不到任何 xy。那么,为什么 plot(mod1) 有效而 plot(summary(mod1)) 无效呢?

输入 plot(x) 时,根据 class(x) 会调用多种方法。这称为方法分派。人们还可以创建新的自己的方法,例如plot.summary.aov 摘要对象:

data <- data.frame(group = c(rep("group_1",25),rep("group_2",25)), scores = c(runif(25,0,1),runif(25,1.5,2.5)))
mod1 <- aov(scores~group,data=data)

plot(mod1)

让我们定义一个新的存根图函数

plot.summary.aov <- function(x) {
  plot(iris)
}

plot(summary(mod1))

methods(plot)
#>  [1] plot.acf*           plot.data.frame*    plot.decomposed.ts*
#>  [4] plot.default        plot.dendrogram*    plot.density*      
#>  [7] plot.ecdf           plot.factor*        plot.formula*      
#> [10] plot.function       plot.hclust*        plot.histogram*    
#> [13] plot.HoltWinters*   plot.isoreg*        plot.lm*           
#> [16] plot.medpolish*     plot.mlm*           plot.ppr*          
#> [19] plot.prcomp*        plot.princomp*      plot.profile.nls*  
#> [22] plot.R6*            plot.raster*        plot.spec*         
#> [25] plot.stepfun        plot.stl*           plot.summary.aov   
#> [28] plot.table*         plot.ts             plot.tskernel*     
#> [31] plot.TukeyHSD*     
#> see '?methods' for accessing help and source code