【问题标题】:Plot multiple functions in R在 R 中绘制多个函数
【发布时间】:2011-01-12 10:47:26
【问题描述】:

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

我尝试做的是:

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

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

【问题讨论】:

    标签: r function statistics plot


    【解决方案1】:

    与您的风格保持一致。例如,始终使用&lt;-,或者始终使用=;不要混搭。以下是来自GoogleHadley Wickham 的一些示例样式指南。

    如果您将read.tablesep=','header=TRUE 一起使用,您可以改为调用read.csv

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

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

    【讨论】:

      【解决方案2】:

      有一个很好的函数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-dependent”(引用磁盘标签),但如果你使用亲戚路径,那么它可能更有用。

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

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

      然后,当您想在窗口中而不是在文件中查看绘图时,搜索正确的行会更容易。

      【讨论】:

        猜你喜欢
        • 2011-01-15
        • 1970-01-01
        • 1970-01-01
        • 2016-07-31
        • 2016-10-20
        • 1970-01-01
        • 1970-01-01
        • 2012-05-14
        • 2018-09-03
        相关资源
        最近更新 更多