[R-sig-teaching] Legend for curve fit plot

Warford, Stan Stan.Warford at pepperdine.edu
Tue Dec 30 23:49:04 CET 2014


Hello all,

I provide a function for my students to do two curve fits with a single set of data:

# Performs two curve fits, quadratic and n lg n, with a plot of the data and the two curves
# First parameter: A data frame
# Second parameter: Name of the independent (x) variable
# Third parameter: Name of the dependent (y) variable
# Fourth parameter: The label for the x-axis
# Fifth parameter: The label for the y-axis
dp4dsFit <- function(dataFrame, indepVarName, depVarName, xLabel, yLabel) {
  library(ggplot2)
  library(labeling)
  dp4dsQuadraticFit <- lm(dataFrame[,depVarName] ~ poly(dataFrame[,indepVarName],2))
  write("=============\r",file="")
  write("Quadratic fit\r",file="")
  write("=============\r",file="")
  print(summary(dp4dsQuadraticFit))
  dp4dsNlogNFit <- lm(dataFrame[,depVarName] ~ dataFrame[,indepVarName]:log(dataFrame[,indepVarName]) + dataFrame[,indepVarName])
  write("==========\r",file="")
  write("n lg n fit\r",file="")
  write("==========\r",file="")
  print(summary(dp4dsNlogNFit))
  ggplot() +
    geom_point(data = dataFrame, aes_string(x = indepVarName, y = depVarName), size = 3) +
    geom_smooth(data = dataFrame, aes_string(x = indepVarName, y = depVarName),
                method = "lm", se = FALSE, colour = "RED", formula = y ~ poly(x,2)) +
    geom_smooth(data = dataFrame, aes_string(x = indepVarName, y = depVarName),
                method = "lm", se = FALSE, colour = "BLUE", formula = y ~ x:log(x) + x) +
    xlab(label = xLabel) +
    ylab(label = yLabel)
}


I use ggplot to produce the plot, but I cannot figure out how to produce the legend. Every example I have seen assumes a separate entry in the legend for each set of data. The problem is I have a single set of data with two different curve fits. How do I make a legend with red for the quadratic curve fit and blue for the n lg n curve fit?

Another minor question. Are the above write statements the best way to echo a message to the console?

Thanks,
Stan

J. Stanley Warford
Professor of Computer Science
Pepperdine University
Malibu, CA 90263
Stan.Warford at pepperdine.edu<mailto:Stan.Warford at pepperdine.edu>
310-506-4332


	[[alternative HTML version deleted]]



More information about the R-sig-teaching mailing list