Base Graphics¶
Building Graphs¶
Incremental building of features into graphs.
References
- Graphical parameters
- Colors
- Named colors - type
colors()
- Using color scales and plattes in R
?plot
?par
- Specific options e.g.
?pch
Basic plots¶
In [1]:
head(mtcars)
Out[1]:
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | |
---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21 | 6 | 160 | 110 | 3.9 | 2.62 | 16.46 | 0 | 1 | 4 | 4 |
Mazda RX4 Wag | 21 | 6 | 160 | 110 | 3.9 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.32 | 18.61 | 1 | 1 | 4 | 1 |
Hornet 4 Drive | 21.4 | 6 | 258 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
Hornet Sportabout | 18.7 | 8 | 360 | 175 | 3.15 | 3.44 | 17.02 | 0 | 0 | 3 | 2 |
Valiant | 18.1 | 6 | 225 | 105 | 2.76 | 3.46 | 20.22 | 1 | 0 | 3 | 1 |
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
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]:
1 | 1 |
2 | 3 |
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 [ ]: