3

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

0

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Darren, I would have never figure it out by myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.