# -------------------------------------------------
# How to create a density plot in R
# -------------------------------------------------
# load library and data
library(mlbench)
data(mtcars)
dim(mtcars)
par(mfrow=c(1,1))
# Density Plot
d <- density(mtcars$mpg)
plot(d, main="Density Plot")
# Filled Density Plot
d <- density(mtcars$mpg)
plot(d, main="Kernel Density of Miles Per Gallon")
polygon(d, col="red", border="blue")
# Compare MPG distributions for cars with
# 4,6, or 8 cylinders
library(sm)
attach(mtcars)
# create value labels
cyl.f <- factor(cyl, levels= c(4,6,8),
labels = c("4 cylinder", "6 cylinder", "8 cylinder"))
# plot densities
sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")
title(main="MPG Distribution by Car Cylinders")