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.