在R中绘制多个函数

3

我之前在这里提问,得到了有关绘制函数的有用信息。我想尝试在同一坐标系上绘制二十个函数,以说明函数在两个范围内的变化情况。我已经成功地使用单独指定的函数完成了这个任务,但是我希望使用循环来实现。

我所尝试的是:

## add ggplot2
library(ggplot2)
library(lattice)

# Declare local variables
inPath = "D:/R_Analysis/"
inFile = "sample.txt"

outPath = "D:/R_Analysis/"
outFile = "processed_sample.txt"

pdfOutPath = "D:/R_Analysis/"
pdfOutFile = "processed_sample.pdf"

# Declare Chart values
y_label = "x-axis"
x_label = "y-axis"
chart_title = "..." 

#####################################################################
## Read in data;  
analysis <- 
read.table(paste(inPath, inFile, sep=""), header=TRUE, sep=",", 
na.strings="NA",  dec=".", strip.white=TRUE)

# Setup pdf
pdf(paste(pdfOutPath, pdfOutFile, sep=""),height=6,width=9)

# make plot object    
p <- qplot(
data = data.frame(x = x, y = y), x, y, xlab = x_label, ylab = y_label, 
enter code herexlim = x_range, main = chart_title  )

# make empty function
eq_dummy = function(x){ 0 }
d = stat_function(fun = eq_dummy)

##############
# LOOP #######

for(i in 1 : 21){                                            
       
        # Specify Variables
        intercept = analysis[i,2]
        slope = analysis[i,3]    
        
        # Define Curve    
        eq <- function(x) { slope * log(x) + intercept }
        
        # Make plot object            
        composite <- stat_function(fun=eq)        
        composite = composite + d       
       
}

print(p + composite)  

# Show warnings
warnings()
 
# close the PDF file
dev.off() 

任何关于语法改进或编程结构的建议都会受到欢迎。谢谢。
2个回答

3

有一个很好的函数file.path,可以创建与操作系统无关的文件路径。您可以在代码中使用它:

inPath = file.path("D:","R_Analysis")
inFile = "sample.txt"
outPath = file.path("D:","R_Analysis")
outFile = "processed_sample.txt"
pdfOutPath = file.path("D:","R_Analysis")
pdfOutFile = "processed_sample.pdf"

并且使用
read.table(file.path(inPath, inFile))
pdf(file.path(pdfOutPath, pdfOutFile))

你的路径是“windows-depende”(指磁盘标签),但如果你使用相对路径,则可能更有用。
另一个提示——你应该尽可能晚地打开图形设备,例如:
pdf(file.path(pdfOutPath, pdfOutFile),height=6,width=9)
print(p + composite)  
dev.off()

这样,当您想在窗口而非文件中查看绘图时,寻找适当的行就更容易了。


1

保持风格一致。例如,始终使用<-或始终使用=;不要混用。以下是GoogleHadley Wickham的一些样式指南示例。

如果您正在使用sep=','header=TRUEread.table,您可能可以调用read.csv

在可能的情况下,请尝试将事物放入函数中,而不是拥有一个长脚本。这可以帮助使代码更易读,作为奖励,您可能最终会得到可以重用于后续分析的代码片段。在这种情况下,我倾向于将创建图形的所有代码移动到函数中(可能还有用于初始化图形和执行绘制部分的子功能)。

R Inferno包含很多关于良好的 R 编程实践的想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接