gpt4 book ai didi

带有循环数据的 Rscript 绘图

转载 作者:行者123 更新时间:2023-12-01 10:00:42 29 4
gpt4 key购买 nike

如果这个问题已经得到解答,但我无法找到我需要的东西,我提前道歉。我想从名为 data1.dat、data2.dat 的文件中绘制一些结果......我设法通过循环导入数据,但我无法使用循环绘制结果。仅绘制第一个数据的结果。以下是我使用的脚本:

for(i in 1:3){
assign( paste("data", i, sep=""),
read.table(file=paste(paste("data", i, sep=""),"_lambda.dat",sep=""),head=TRUE, sep=" "))
}

#plot
for(i in 1:3){
if(i==1){
plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE)
} else {
lines(data.frame(paste("data", i, "[1]", sep=""), paste("data", i, "[2]", sep="")) ,lty="twodash", col="deepskyblue4", lwd=4)
}
}

问题与“else”之后的部分有关。没有绘制数据,我也没有收到任何错误消息。

感谢您的帮助,

最佳答案

assign 几乎没有任何有意义的用途。使用列表可以更轻松地完成上述操作:

# Read the data by inserting each data.frame into our list.
data <- list()
for (i in 1:3) {
data[[i]] <- data.frame(runif(10), rnorm(10)) # Replace with your call to read.table.
}

# As we are lazy, we can pre-save our styles and just use them later
ltys <- c('solid', 'twodash', 'twodash')
cols <- c('red', 'deepskyblue4', 'deepskyblue4')

# Creating the empty plot first allows us to do everything else with lines. Note that there are a ton of different ways to archive this.
plot(NA, xlim=c(0,1), ylim=c(-2,2))
# And now we just may access the data by using the lists.
for (i in 1:length(data)) {
d <- data[[i]]
lines(d[,1], d[,2], lty=ltys[i], col=cols[i], lwd=4)
}

如果我们的目标是优雅,我们甚至可以使用完全不同的方法:

# This time we will read all data into one data.frame.
# This requires the data to be of the same form, however.
data <- data.frame()
for (i in 1:3) {
d <- data.frame(x=runif(10), y=rnorm(10))
# Here is the trick: We add the index i (or a file name, or something totally different) as a separate column.
data <- rbind(data, cbind(d, group=i))
}
# This is just to ensure that our group column is a factor.
data$group <- as.factor(data$group)

# Now, plotting could be done by various ways. Personally, I like the elegance of ggplot2.
library(ggplot2)
qplot(x,y,data=data, col=group, geom="line")

关于带有循环数据的 Rscript 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16750104/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com