R Graphics

In [1]:
options.orig <- options(repr.plot.width=4, repr.plot.height=4)

Base Graphics

This is the graphics you get ont of the box, without loading any packages. It is not the prettiest, but great for quick plotting.

Scatter plot

In [2]:
plot(1:10, 1:10)
../_images/cliburn_R_Graphics_Base_4_0.png

Rotate labels

In [3]:
plot(1:10, 1:10, las=1)
../_images/cliburn_R_Graphics_Base_6_0.png

Marker symbols

In [4]:
plot(1:10, 1:10, pch=1:10)
../_images/cliburn_R_Graphics_Base_8_0.png

Marker size

In [5]:
plot(1:10, 1:10, pch=1:10, cex=1:10)
../_images/cliburn_R_Graphics_Base_10_0.png

Marker colors

In [6]:
plot(1:10, 1:10, pch=1:10, cex=1:10, col=1:10)
../_images/cliburn_R_Graphics_Base_12_0.png

Adding text labels

In [7]:
plot(1:10, 1:10, pch=1:10, col=1:10, xlim=c(0, 11))
text(1:10+1, 1:10, 1:10)
../_images/cliburn_R_Graphics_Base_14_0.png

Line plot

In [8]:
n <- 20
x <- 1:n
y <- x + rnorm(n)

plot(x, y, type="l", lty=1, lwd=2, col="red",
     main="Plot", xlab="Foo", ylab="Bar")
points(x, y, col="blue")
../_images/cliburn_R_Graphics_Base_16_0.png
In [9]:
m <- lm(y ~ x)
plot(x, y, col="blue")
abline(m, col="red", lty="dashed")
../_images/cliburn_R_Graphics_Base_17_0.png

Histogram

In [10]:
hist(y)
../_images/cliburn_R_Graphics_Base_19_0.png

Barplot

In [11]:
barplot(y)
../_images/cliburn_R_Graphics_Base_21_0.png
In [12]:
g <- sample(1:3, n, replace=T)
z <- rnorm(n)
In [13]:
boxplot(z ~ g)
../_images/cliburn_R_Graphics_Base_23_0.png

QQ plots

In [14]:
x <- rnorm(100)
In [15]:
qqnorm(x)
qqline(x)
../_images/cliburn_R_Graphics_Base_26_0.png
In [16]:
y <- rgamma(100, shape=1)
In [17]:
qqnorm(y)
qqline(y)
../_images/cliburn_R_Graphics_Base_28_0.png

Multiple plots

We can set up multiple plots with

par(mfrow=c(#rows, #cols))

where plots will be placed by row first

or

par(mfcol=c(#rows, #cols))

where plots will be placed by colum first.

In [18]:
options.orig <- options(repr.plot.width=6, repr.plot.height=6)
In [19]:
par(mfrow=c(2,2))
plot(x, y)
plot(x, y, type="l")
barplot(x)
barplot(y)
par(mfrow=c(1,1))
../_images/cliburn_R_Graphics_Base_31_0.png

Saving plots

Saving a plot involves

  • opening a graphcis file device using png (or pdf)
  • issuing plot commands
  • then closing the device with dev.off().
In [20]:
png('figs/lm.png')
m <- lm(y ~ x)
plot(x, y, col="blue")
abline(m, col="red", lty="dashed")
dev.off()
png: 2

Retreive the PNG file

Image

Image