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

Overlaying a density line over a histogram


In this recipe, we will learn how to superimpose a kernel density line on top of a histogram.

Getting ready

We will continue using the airpollution.csv example dataset. You can simply type in the recipe code at the R prompt. If you wish to use the code later, you should save it as a script file. First, let's load the data file.

air<-read.csv("airpollution.csv")

How to do it...

Let's overlay a line that shows the kernel density of respirable particle concentrations on top of a probability distribution histogram:

par(yaxs="i",las=1)
hist(air$Respirable.Particles,
prob=TRUE,col="black",border="white",
xlab="Respirable Particle Concentrations",
main="Distribution of Respirable Particle Concentrations")
box(bty="l")

lines(density(air$Respirable.Particles,na.rm=T),col="red",lwd=4)
grid(nx=NA,ny=NULL,lty=1,lwd=1,col="gray")

How it works...

The code for the histogram itself is exactly the same as in the previous recipe. After making the hist() function call...