Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Adding nonparametric model curves with lowess


In this recipe, we will learn how to use lowess, which is a nonparametric model, and add the resulting prediction curve to a scatter plot.

Getting ready

For this recipe, we don't need to load any additional libraries. We just need to type the recipe in the R prompt or run it as a script.

How to do it...

First, let's create a simple scatter plot with the preloaded cars dataset and add a couple of lowess lines to it:

plot(cars, main = "lowess(cars)")
lines(lowess(cars), col = "blue")
lines(lowess(cars, f=0.3), col = "orange")

How it works...

Standard R sessions include the lowess() function. It is a smoother that uses locally weighted polynomial regression. The first argument, in this instance, is a data frame called cars that gives the x and y variables (speed and dist). So we apply the lowess function to the cars dataset and in turn pass that result to the lines() function. The result of lowess is a list with components named x and y. The lines() function...