Base Graphics

Building Graphs

Incremental building of features into graphs.

Less is more

More visualization tips

References

  1. Graphical parameters
  2. Colors
  3. Named colors - type colors()
  4. Using color scales and plattes in R
  5. ?plot
  6. ?par
  7. Specific options e.g. ?pch

Basic plots

In [1]:
head(mtcars)
Out[1]:
mpgcyldisphpdratwtqsecvsamgearcarb
Mazda RX42161601103.92.6216.460144
Mazda RX4 Wag2161601103.92.87517.020144
Datsun 71022.84108933.852.3218.611141
Hornet 4 Drive21.462581103.083.21519.441031
Hornet Sportabout18.783601753.153.4417.020032
Valiant18.162251052.763.4620.221031
In [8]:
plot(mtcars$wt, mtcars$mpg)
In [9]:
scatter.smooth(mtcars$wt, mtcars$mpg)
In [10]:
df <- mtcars[order(mtcars$wt),]
plot(df$wt, df$mpg, type="b")
In [11]:
hist(mtcars$mpg, breaks=10)
In [12]:
plot(density(mtcars$mpg), main="Density plot")
In [13]:
hist(mtcars$mpg, breaks=10, probability = TRUE, main="")
rug(mtcars$mpg)
x <- seq(min(mtcars$mpg), max(mtcars$mpg), length.out = 50)
lines(x, dnorm(x, mean=mean(x), sd=sd(x)), col="red", lwd=2)
In [14]:
pie(table(mtcars$carb))
In [15]:
barplot(table(mtcars$carb))
In [16]:
barplot(table(mtcars$carb), horiz=TRUE)
In [18]:
(tbl <- table(mtcars$carb, mtcars$am))
barplot(tbl, beside=TRUE, legend=rownames(tbl), col=heat.colors(mtcars$carb))
Out[18]:

0 1
  1 3 4
  2 6 4
  3 3 0
  4 7 3
  6 0 1
  8 0 1
In [19]:
boxplot(log1p(mtcars))
In [20]:
df <- mtcars[order(-mtcars$mpg),]
dotchart(df$mpg, labels=row.names(df))
In [21]:
dotchart(df$mpg, labels=row.names(df), groups=df$cyl, color=df$cyl, pch=19)
In [22]:
pairs(~mpg + drat + wt, data=mtcars)

Building plots

  • Local customization of plots
  • Glaobl customization of plots
  • Adding more stuff to a plot
    • points
    • lines
    • text
    • mathematical expressions
  • Combining plots
  • Saving plots

Scatterplot

In [23]:
df <- mtcars[order(mtcars$wt),]
plot(df$wt, df$mpg)

Combining plots

In [24]:
par(mfrow=c(2,2))
plot(rnorm(10))
plot(rnorm(10))
plot(rnorm(10))
plot(rnorm(10))
In [25]:
(m <- matrix(c(1,1,2,3), 2, 2, byrow=TRUE))
Out[25]:
11
23
In [26]:
layout(m)
plot(rnorm(10))
plot(rnorm(10))
plot(rnorm(10))
In [27]:
layout(m, widths=c(1,2), heights=c(2,1))
plot(rnorm(10))
plot(rnorm(10))
plot(rnorm(10))
In [28]:
orig <- par(no.readonly=TRUE)
x <- rnorm(10)
y <- rnorm(10)
par(fig = c(0, 0.8, 0, 0.8))
plot(x, y)
par(fig = c(0, 0.8, 0.6, 1), new=TRUE)
plot(density(x), axes=FALSE, main="", xlab="")
par(fig = c(0.6, 1, 0, 0.8), new=TRUE)
boxplot(y, axes=FALSE)
par(orig)
In [ ]: