一次制作多个直方图并保存

Make multiple histograms at once and save them

我想制作数据集第 5-34 列的直方图并保存以供参考。这就是我所拥有的,错误 'x must be numeric' 不断出现。所有这些列都有数字数据。

[资料截图][1]

dput(longbroca)
histograms = c()
GBhistograms = c()
RThistograms = c()
for (i in 5:34){

  hist(longbroca)
  hist(GBlongbroca)
  hist(RTlongbroca)

  histograms = c(histograms, hist(longbroca[,5:34]))
GBhistograms = c(GBhistograms, hist(GBlongbroca[,5:34]))
RThistograms = c(RThistograms, hist(RTlongbroca[,5:34]))

}

#reproducible
fakerow1 <- c(100,80,60,40,20)
fakerow2 <- c(100,80,60,40,20)
fakedata = rbind(fakerow1,fakerow2)
colnames(fakedata) = c('ant1','ant2','ant3','ant4','ant5')

您无法使用单个 hist() 函数绘制所有列。这就是您收到错误消息的原因。您正在绘制直方图并保存直方图中的输出列表。您的代码不保存任何直方图,只保存用于生成直方图的数据。如果您真的想保存绘制的直方图,则需要将它们绘制到设备上(例如 pdf)。

我们可以使用 R (data(iris)) 附带的 iris 数据集作为示例数据。前 4 列是数字。如果您只想要来自 iris 数据集(第 1 至 4 列)的直方图数据:

# R will plot all four but you will only see the last one.
histograms <- lapply(iris[, 1:4], hist)

变量histograms是一个包含6个元素的列表。这些记录在函数的手册页上 (?hist)。

# To plot one of the histograms with a title and x-axis label:
lbl <- names(histograms)
plot(histograms[[1]], main=lbl[1], xlab=lbl[1])

# To plot them all
pdf("histograms.pdf")
lapply(1:4, function(x) plot(histograms[[x]], main=lbl[x], xlab=lbl[x]))
dev.off()

文件 "histograms.pdf" 将包含所有四个直方图,每页一个。