在 R 中绘制多个函数

发布于 2024-08-20 05:36:47 字数 1658 浏览 2 评论 0原文

我之前问过这个问题,它在绘制函数时很有用。我想尝试在同一轴上绘制二十个函数,以说明函数在两个范围之间如何变化。我已经使用单独指定的函数成功完成了此操作,但我想使用循环来完成此操作。

我尝试做的是:

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

任何有关语法改进或编程结构的建议将不胜感激。谢谢。

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. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜嗑 2024-08-27 05:36:47

有一个很好的函数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))

Your path is“windows-dependent”(参考磁盘标签),但如果您使用相对路径,那么它可能会更有用。

第二个提示 - 您应该尽可能晚地打开图形设备,例如,

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

当您想在窗口而不是文件中查看绘图时,可以更轻松地搜索正确的行。

There is nice function file.path which allow to create file paths OS independent. 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.

And second hint - you should open graphics device as late as possible, e.g.

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.

眼眸印温柔 2024-08-27 05:36:47

与您的风格保持一致。例如,始终使用 <-,或始终使用 =;不要混合搭配。以下是来自 Google 和 < a href="http://had.co.nz/stat405/resources/r-style-guide.html" rel="nofollow noreferrer">哈德利·威克姆。

如果您将 read.tablesep=','header=TRUE 一起使用,则可以调用 read.csv< /代码> 相反。

只要有可能,尝试将东西放在函数中,而不是使用一个很长的脚本。这有助于使代码更具可读性,而且作为奖励,您最终可能会得到一些可以重复使用以供以后分析的代码。在这种情况下,我很想将创建绘图的所有代码移动到一个函数中(可能带有用于初始化绘图和执行绘图部分的子函数)。

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

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.

If you are using read.table with sep=',' and header=TRUE, you can probably call read.csv instead.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文