From statmethods.net.
# ggplot2 examples
library(ggplot2)
#use color brewer as default discrete colors
scale_colour_discrete <- function(...) scale_color_brewer(palette="Set1", ...)
scale_fill_discrete <- function(...) scale_fill_brewer(palette="Set1", ...)
data('mtcars')
# create factors with value labels
mtcars$gear <- factor(mtcars$gear,levels=c(3,4,5),
labels=c("3gears","4gears","5gears"))
mtcars$am <- factor(mtcars$am,levels=c(0,1),
labels=c("Automatic","Manual"))
mtcars$cyl <- factor(mtcars$cyl,levels=c(4,6,8),
labels=c("4cyl","6cyl","8cyl"))
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear
## Mazda RX4 21.0 6cyl 160 110 3.90 2.620 16.46 0 Manual 4gears
## Mazda RX4 Wag 21.0 6cyl 160 110 3.90 2.875 17.02 0 Manual 4gears
## Datsun 710 22.8 4cyl 108 93 3.85 2.320 18.61 1 Manual 4gears
## Hornet 4 Drive 21.4 6cyl 258 110 3.08 3.215 19.44 1 Automatic 3gears
## Hornet Sportabout 18.7 8cyl 360 175 3.15 3.440 17.02 0 Automatic 3gears
## Valiant 18.1 6cyl 225 105 2.76 3.460 20.22 1 Automatic 3gears
## carb
## Mazda RX4 4
## Mazda RX4 Wag 4
## Datsun 710 1
## Hornet 4 Drive 1
## Hornet Sportabout 2
## Valiant 1
qplot(mpg, data=mtcars, geom="density", fill=gear, alpha=I(.5),
main="Distribution of Gas Milage", xlab="Miles Per Gallon",
ylab="Density")
qplot(hp, mpg, data=mtcars, shape=am, color=am,
facets=gear~cyl, size=I(3),
xlab="Horsepower", ylab="Miles per Gallon")
ggplot(mtcars, aes(wt, mpg, color = cyl)) +
geom_point() +
geom_smooth(method = "lm", formula = y~x) +
labs(title = "Regression of MPG on Weight", x = "Weight", y = "Miles per Gallon")
qplot(gear, mpg, data=mtcars, geom=c("boxplot", "jitter"),
fill=gear, main="Mileage by Gear Number",
xlab="", ylab="Miles per Gallon")