Search code examples
rapplygraphing

Making multiple graphs with apply function and showing variable name in header


I'm trying to make multiple graphs with the apply function of R. However, I cannot make it to show the variable name in the header. I'd really appreciate it if anyone can help me with this issue.

This is the following code:

x <- c(rnorm(10), runif(10), rnorm(10,1))
y <- c(rnorm(10), runif(10), rnorm(10,1))
data <- cbind(x,y)
df <- as.data.frame(data)

apply(df, 2, plottingfunction <- function(x) {
  plot(x, type= "line", main = paste("This is the graph of ", colnames(df) ))
})

The code is not going to work, however if anyone can fix it so that the graph show the name of the variable in the header would be great.

Thanks in advance for your help


Solution

  • First, you need to set the graphical parameter mfrow or mfcol to define the layout of multiple plots. And in your case, mapply is more suitable.

    par(mfrow = c(1, 2))
    mapply(function(data, title){
      plot(data, type = "l", main = paste("This is the graph of ", title))
    }, df, names(df))
    

    enter image description here

    • mfrow = c(1, 2) means subsequent figures will be drawn in an 1-by-2 array on the device by rows.