Import and preprocess data.
library(MASS)
attach(Boston)
data = as.data.frame(na.omit(Boston))
names(data)
## [1] "crim" "zn" "indus" "chas" "nox" "rm" "age"
## [8] "dis" "rad" "tax" "ptratio" "black" "lstat" "medv"
smp.idx = sample(1:nrow(data), 5) # sample 5 rows from the raw data set
y1 = data[smp.idx, 3] # column 3 for the sampled rows
y2 = data[smp.idx, 6] # column 6 for the sampled rows
y3 = data[smp.idx, 7] # column 9 for the sampled rows
new.data = rbind(y1, y2, y3)
labels = paste("S", 1:length(y1), sep="")
legends = c("indus", "rm", "rad")
Produce a simple bar plot of Ozone.
barplot(y2, ylim=c(0,max(y2)*1.2), offset=0,
axis.lty=1, names.arg=labels, ylab="Value")
Produce a bar plot with box.
barplot(y2, ylim=c(0,max(y2)*1.2), offset=0,
axis.lty=1, names.arg=labels, ylab="Value")
box()
Produce a stacked bar plot in terms of sample.
# Add extra space to right of plot area
par(mar=c(5.1, 4.1, 4.1, 5.1), xpd=TRUE)
barplot(new.data, ylim=c(0,max(y1+y2+y3)*1.2), offset=0,
axis.lty=1, names.arg=labels, ylab="Value",
col=terrain.colors(3))
legend("right", inset=c(-0.2,0), legend=legends,
fill=terrain.colors(3), box.col="transparent")
Produce a grouped bar plot in terms of sample.
# Add extra space to right of plot area
par(mar=c(5.1, 4.1, 4.1, 5.1), xpd=TRUE)
barplot(new.data, ylim=c(0,max(new.data)*1.2), offset=0,
axis.lty=1, names.arg=labels, ylab="Value",
col=terrain.colors(3), beside=TRUE)
legend("right", inset=c(-0.2,0), legend=legends,
fill=terrain.colors(3), box.col="transparent")
Produce a grouped bar plot in terms of feature.
# Add extra space to right of plot area
par(mar=c(5.1, 4.1, 4.1, 5.1), xpd=TRUE)
barplot(t(new.data), ylim=c(0,max(new.data)*1.2), offset=0,
axis.lty=1, names.arg=legends, ylab="Value",
col=terrain.colors(length(labels)), beside=TRUE)
legend("right", inset=c(-0.2,0), legend=labels,
fill=terrain.colors(length(labels)), box.col="transparent")
# Add extra space to right of plot area
par(mar=c(5.1, 4.1, 4.1, 5.1), xpd=TRUE)
x = barplot(new.data, ylim=c(0,max(new.data)*1.2), offset=0,
axis.lty=1, names.arg=labels, ylab="Value",
col=terrain.colors(3), beside=TRUE)
legend("right", inset=c(-0.2,0), legend=legends,
fill=terrain.colors(3), box.col="transparent")
plot.error = function (x, y, sd, len=1, col="black", horiz=FALSE) {
len=len*0.05
if(!horiz){
arrows(x0=x, y0=y, x1=x, y1=y-sd, col=col, angle=90, length=len)
arrows(x0=x, y0=y, x1=x, y1=y+sd, col=col, angle=90, length=len)
}
else{
arrows(x0=y, y0=x, x1=y-sd, y1=x, col=col, angle=90, length=len)
arrows(x0=y, y0=x, x1=y+sd, y1=x, col=col, angle=90, length=len)
}
}
sd = new.data*0.1
for (i in 1:3) plot.error(x[i,], new.data[i,], sd=sd[i,])