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 error bars


In most scientific data visualizations, error bars are required to show the level of confidence in the data. However, there is no predefined function in the base R library to draw error bars. In this recipe, we will learn how to draw error bars in scatter plots.

Getting ready

All you need for the next recipe is to type it at the R prompt as we will use some base library functions to define a new error bar function. You can also save the recipe's code as a script so that you can use it again later on.

How to do it...

Let's draw vertical error bars with 5 percent errors on our cars' scatter plot using the arrows() function:

plot(mpg~disp,data=mtcars)

arrows(x0=mtcars$disp,
y0=mtcars$mpg*0.95,
x1=mtcars$disp,
y1=mtcars$mpg*1.05,
angle=90,
code=3,
length=0.04,
lwd=0.4)

To add horizontal error bars (also 5 percent in both directions) to the same graph, run the following code after creating the preceding graph:

arrows(x0=mtcars$disp*0.95,
y0=mtcars$mpg,
x1=mtcars$disp*1.05,
y1=mtcars...