使用 apply 函数制作多个图形并在 header 中显示变量名称

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

我正在尝试使用 R 的应用功能制作多个图表。但是,我无法让它在 header 中显示变量名称。如果有人能帮助我解决这个问题,我将不胜感激。

这是下面的代码:

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) ))
})

该代码无法正常工作,但是如果有人可以修复它以便图形显示 header 中的变量名称,那就太好了。

提前感谢您的帮助

首先,您需要设置图形参数mfrowmfcol来定义多个地块的布局。而你的情况,mapply更合适。

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

  • mfrow = c(1, 2) 表示后续图形将按行绘制在设备上的 1×2 数组中。