简体   繁体   English

在R中绘制多个函数

[英]Plot multiple functions in R

I previously asked this question which was useful in plotting a function. 我之前问过这个问题 ,这个问题在绘制函数时非常有用。 I want to try and plot twenty functions on the same axes to illustrate how a function varies between two ranges. 我想尝试在相同的轴上绘制20个函数,以说明函数在两个范围之间的变化。 I have successfully done this using individually specified functions, but I wanted to do this using a loop. 我已经使用单独指定的函数成功完成了此操作,但我想使用循环来完成此操作。

What I have attempted doing is: 我试图做的是:

## 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() 

Any suggestions about syntax improvement, or programming structure would be appreciated. 任何有关语法改进或编程结构的建议都将受到赞赏。 Thank you. 谢谢。

There is nice function file.path which allow to create file paths OS independent. 有一个很好的函数file.path ,它允许创建独立于OS的文件路径。 You could use it in your code as: 您可以在代码中使用它:

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"

and then use 然后使用

read.table(file.path(inPath, inFile))
pdf(file.path(pdfOutPath, pdfOutFile))

Your path is "windows-depended" (reference to disk label), but if you use relatives paths then it could be more useful. 您的路径是“windows-depended”(对磁盘标签的引用),但如果您使用亲戚路径,那么它可能会更有用。

And second hint - you should open graphics device as late as possible, eg 第二个提示 - 你应该尽可能晚地打开图形设备,例如

pdf(file.path(pdfOutPath, pdfOutFile),height=6,width=9)
print(p + composite)  
dev.off()

Then it's easier to search for proper line when you want to see plot in window and not in file. 然后,当您想要在窗口而不是文件中查看绘图时,更容易搜索正确的行。

Be consistent with your style. 与你的风格保持一致。 For example, always use <- , or always use = ; 例如,始终使用<- ,或始终使用= ; don't mix and match. 不要混搭。 Here are some example style guides from Google and Hadley Wickham . 以下是GoogleHadley Wickham的一些示例风格指南。

If you are using read.table with sep=',' and header=TRUE , you can probably call read.csv instead. 如果你使用带有sep=','header=TRUE read.table ,你可以改为调用read.csv

Wherever possible, try to place things in functions rather than having one long script. 尽可能尝试将内容放在函数中而不是使用一个长脚本。 This can help make the code more readable, and as a bonus you may end up with bits of code you can reuse for later analyses. 这可以帮助使代码更具可读性,作为奖励,您最终可能会重复使用一些代码,以便以后进行分析。 In this case, I'd be tempted to move all the code that creates the plot into a function (possibly with subfunctions for initialising the plot and for doing the drawing part). 在这种情况下,我很想将创建绘图的所有代码移动到一个函数中(可能使用子函数来初始化绘图和绘制绘图部分)。

The R Inferno contains lots of ideas on good R programming practice. R Inferno包含许多关于良好R编程实践的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM