【发布时间】:2023-04-01 12:37:01
【问题描述】:
StackOverflow 对我的帮助很大,但我无法将所有内容放在一起。
我想从 txt 文件中存储的数据自动生成直方图。每个文件包含一个数据列。
这是我写的原始代码,它可以工作:
#!/usr/bin/env Rscript
#for all .txt files in a directory
for(i in 1:length(list.files(pattern="*.txt")))
{
#reading data
histo = read.table(list.files(pattern="*.txt")[i])
#cutting off ".txt"
name = list.files(pattern="*.txt")[i]
name = strsplit(name, ".", fixed=TRUE)[[1]]
name = name[1]
png(name)
hist(
main = paste("Histogram dla probki" , name),
histo$V1,
breaks = 10,
freq = FALSE,
#looks
col = "gray",
tck = -0.015,
#labels
xlab = "srednica [um]",
ylab = "gestosc"
)
box()
dev.off()
}
这是它的外观: http://i.stack.imgur.com/GYprl.png
我想将 y 轴更改为百分比并为每一列添加标签,如下所示: http://www.ats.ucla.edu/stat/sas/faq/histogram_anno_hist_ods.png
我更改了我的代码,实现了我在 SO 和其他网站上找到的内容,我更正了我遇到的任何错误。当我运行脚本时,它不会返回任何错误,并且似乎可以正常工作。但是,它也不会生成任何图片。
新代码如下所示:
#!/usr/bin/env Rscript
for(i in 1:length(list.files(pattern="*.txt")))
{
#reading data
histo = read.table(list.files(pattern="*.txt")[i])
#cutting off ".txt"
name = list.files(pattern="*.txt")[i]
name = strsplit(name, ".", fixed=TRUE)[[1]]
name = name[1]
histPercent <- function(histo)
{
png(name)
h <- hist(histo$V1, plot = FALSE)
h$density <- with(h, 100*density*diff(breaks)[1])
labs <- paste(round(h$density), "%", sep="")
plot(h,
main = paste("Histogram dla próbki " , name),
histo$V1,
breaks = 10,
freq = FALSE,
#looks
col = "green",
tck = -0.015,
labels = labs,
xlab = "średnica [um]",
ylab = "udział procentowy"
)
dev.off()
}
#box()
}
怎么了?我还尝试在函数之外使用 png() 和 dev.off()。
【问题讨论】:
-
您是否在脚本中的任何位置调用 histPercent 函数?