Home > front end >  How does `plot` know how to plot an object without further specification?
How does `plot` know how to plot an object without further specification?

Time:12-14

With R base function plot we can make different plots just by providing the data, without specifying further arguments. For example, if we plot a time series, using plot(my_ts) calls plot.ts(my_ts) because my_ts is class ts.

Similarly, we can use plot ANOVA results without any arguments. Here some ANOVA model:

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)

Using plot(mod1) works but plot(summary(mod1)) results in the error "Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' is a list, but does not have components 'x' and 'y'". It seems like the plot function looks for data named x and y while trying to automatically create a plot without any arguments. I tried names(mod1) but couldn't find any x or y. So how does it come that plot(mod1) works but plot(summary(mod1)) does not?

CodePudding user response:

There are multiple methods which are called depending on class(x) when typing plot(x). This is called method dispatch. One can also create new own methods e.g. plot.summary.aov for summary objects:

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)

Let's define a new stub plot function

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
  • Related