首页 > 解决方案 > 一次制作多个直方图并保存

问题描述

我想制作我的数据集第 5-34 列的直方图并将它们保存以供参考。这就是我所拥有的,并且不断出现错误“x 必须是数字”。所有这些列都有数字数据。

[数据截图][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')

标签: rhistogram

解决方案


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

我们可以使用irisR ( ) 附带的数据集data(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”将包含所有四个直方图,每页一个。


推荐阅读