# R in Action (2nd ed): Chapter 6 # Basic graphs # requires packages vcd, plotrix, sm, vioplot to be installed install.packages(c("vcd", "plotrix", "sm", "vioplot")) #------------------------------------------------------------ # kernel density plot install.packages("sm") par(mfrow=c(2,1)) ?par # par function with mfrow option to figures to be arranged accordingly, in this case 2 lines one column # <- coment 1 d <- density(mtcars$mpg) # returns the density data plot(d) # plots the results d <- density(mtcars$mpg) plot(d, main="Kernel Density of Miles Per Gallon") polygon(d, col="red", border="blue") rug(mtcars$mpg, col="brown") par(lwd=2) library(sm) attach(mtcars) # create value labels cyl.f <- factor(cyl, levels= c(4, 6, 8), labels = c("4 cylinder", "6 cylinder", "8 cylinder")) cyl.f head(cyl.f) tail(cyl.f) summary(cyl.f) # plot densities sm.density.compare(mpg, cyl, xlab="Miles Per Gallon") title(main="MPG Distribution by Car Cylinders") # add legend via mouse click colfill<-c(2:(2+length(levels(cyl.f)))) cat("Use mouse to place legend...","\n\n") legend(locator(1), levels(cyl.f), fill=colfill) detach(mtcars) par(lwd=1) # box plots boxplot(mtcars$mpg, main="Box plot", ylab="Miles per Gallon") mtcars boxplot.stats(mtcars$mpg) # parallel box plots boxplot(mpg~cyl,data=mtcars, main="Car Milage Data", xlab="Number of Cylinders", ylab="Miles Per Gallon") # notched box plots boxplot(mpg~cyl,data=mtcars, notch=TRUE, varwidth=TRUE, col="red", main="Car Mileage Data", xlab="Number of Cylinders", ylab="Miles Per Gallon") # create a factor for number of cylinders mtcars$cyl.f <- factor(mtcars$cyl, levels=c(4,6,8), labels=c("4","6","8")) # create a factor for transmission type mtcars$am.f <- factor(mtcars$am, levels=c(0,1), labels=c("auto","standard")) # generate boxplot boxplot(mpg ~ am.f *cyl.f, data=mtcars, varwidth=TRUE, col=c("gold", "darkgreen"), main="MPG Distribution by Auto Type", xlab="Auto Type") #VIOLIN PLOTS library(vioplot) x1 <- mtcars$mpg[mtcars$cyl==4] x2 <- mtcars$mpg[mtcars$cyl==6] x3 <- mtcars$mpg[mtcars$cyl==8] vioplot(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"), col="gold") title("Violin Plots of Miles Per Gallon", ylab="Miles Per Gallon", xlab="Number of Cylinders")