Rhonda Reidy wrote: > > The following variables have the following significant relationships (x is > the explanatory variable): linear, cubic, exponential, logistic. The > linear relationship plots without any trouble. > > Cubic is the 'best' model, but it is not plotting as a smooth curve using > the following code: > > cubic.lm<- lm(y~poly(x,3)) > lines(x,predict(cubic.lm),lwd=2) > > How do I plot the data and the estimated curves for all of these > regression models in the same plot? > > x <- c(62.5,68.5,0,52,0,52,0,52,23.5,86,0,0,0,0,0,0,0,0,0,0) > > y <- > c(0.054,0.055,0.017,0.021,0.020,0.028,0.032,0.073,0.076,0.087,0.042,0.042,0.041,0.045,0.021,0.018,0.017,0.018,0.028,0.022) >
Hi Rhonda, The problem is that the default behavior of predict() only produces output corresponding to the original values of x used in the model. To get a "smooth" curve, you will want to predict at a large number of x values that fall within the range of the data. This can be done using the pretty() function, or using a composition of the seq() and range() functions if you desire more control: # Create a new vector of X values at which to generate predictions: predX <- pretty( x, n = 100 ) plot( y ~ x ) # Add the regression model, but generate predictions using the # points in predX-- the default is to predict using points in x. lines( predX, predict( cubic.lm, newdata = list( x = predX )), lwd = 2 ) The above should produce the output you want. However, I suggest Hadley Wickham's excellent ggplot2 package-- I feel the following is more expressive than using base graphics functions: require( ggplot2 ) Plot <- qplot( x, y ) + stat_smooth( method = 'lm', formula = 'y ~ poly(x,3)' ) print( Plot ) The amazing power of ggplot2 is that when you want to alter or extend your plot, you simply "add" more ggplot2 commands to your plot object: # Add a linear regression model and change the color theme used in the output Plot <- Plot + stat_smooth( method = 'lm', color = 'red' ) + theme_bw() print( Plot ) Hope this helps! -Charlie -- View this message in context: http://n4.nabble.com/Plot-different-regression-models-on-one-graph-tp1554606p1554622.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.