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

Creating a layered plot with a scatter plot and fitted line


To visualize a relation between two numeric variables, we usually create a scatter plot. We also add a fitted line or smooth curve to the scatter plot, which represents the majority of the data points. In this recipe, we will see how we can produce a scatter plot and then add a layer of fitted line along with a linear smooth and curved line. The curved line could be the lowess or local regression, but here, is loess the default.

Getting ready

Once again, we recall ggplotdata for this plot. In this case, we will use the two numeric variables, which are disA and disD.

How to do it...

Perform the following steps:

  1. We can easily produce the scatter plot with the ggplot function along with the geom point options, as follows:

    Sctrplot <- ggplot(data=ggplotdata,aes(x=disA,y=disD))+geom_point()
  2. We will add a layer of fitted linear line to the scatter plot object, as follows:

    Sctrplot <- Sctrplot + geom_smooth(method="lm",col="red")
  3. Now, we...