【问题标题】:Make multiple histograms at once and save them一次制作多个直方图并保存
【发布时间】:2019-11-20 13:05:11
【问题描述】:

我想制作我的数据集第 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')

【问题讨论】:

  • 您能否通过dput() 函数分享您的数据样本?
  • 您没有使用i 来引用特定列。你的意思是hist(longbroca[,i]) 等等?
  • 添加了数据样本,我添加了hist(longbroca[,i]),我得到了同样的错误
  • 通常人们将 dput() 的控制台输出复制到代码块中。或者将一些模拟数据放入代码块中。

标签: r histogram


【解决方案1】:

您无法使用单个 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”将包含所有四个直方图,每页一个。

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多