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

Histograms in the margins of line and scatter plots


In this recipe, we will learn how to draw histograms in the top and right margins of a bivariate scatter plot.

Getting ready

We will use the airpollution.csv example dataset for this recipe. So, let's make sure it is loaded:

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

How to do it...

Let's make a scatter plot showing the relationship between concentrations of respirable particles and nitrogen oxides with histograms of both the variables in the margins:

#Set up the layout first
layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), widths=c(3,1), 
heights=c(1,3), TRUE)

#Make Scatterplot
par(mar=c(5.1,4.1,0.1,0))
plot(air$Respirable.Particles~air$Nitrogen.Oxides,
pch=19,col="black",
xlim=c(0,600),ylim=c(0,80),
xlab="Nitrogen Oxides Concentrations",
ylab="Respirable Particle Concentrations")

#Plot histogram of X variable in the top row
par(mar=c(0,4.1,3,0))
hist(air$Nitrogen.Oxides,
breaks=seq(0,600,100),ann=FALSE,axes=FALSE,
col="black",border="white")

#Plot histogram...