First published by Slawa Rokicki on the "R for Public Health"-blog at http://rforpublichealth.blogspot.dk
|
library(ggplot2)
|
|
library(gridExtra)
|
|
mtc <- mtcars
|
|
# Basic scatterplot
|
|
p1 <- ggplot(mtc, aes(x = hp, y = mpg))
|
|
# Print plot with default points
|
|
p1 + geom_point()
|
|
#set one color for all points
|
|
p1 + geom_point(color="red")
|
|
#set color scale by a continuous variable
|
|
p1 + geom_point(aes(color = wt))
|
|
#set color scale by a factor variable
|
|
p1 + geom_point(aes(color=factor(am)))
|
|
#increase all points to size 5
|
|
p2 <- p1 + geom_point(size = 5)
|
|
#set point size by continuous variable
|
|
p3 <- p1 + geom_point(aes(size = wt))
|
|
#set point shape by factor variable
|
|
p4 <- p1 + geom_point(aes(shape = factor(am)))
|
|
#connect points with line
|
|
p1 + geom_point(color="blue") + geom_line()
|
|
#add regression line
|
|
p1 + geom_point(color="red") + geom_smooth(method = "lm", se = TRUE)
|
|
#add vertical line
|
|
geom_point() + geom_vline(xintercept = 100, color="red")
|
|
#label all axes at once
|
|
p2 + labs(x="Horsepower",
|
|
y = "Miles per Gallon")
|
|
#label and change font size
|
|
p2 + theme(axis.title.x = element_text(face=
|
|
"bold", size=20)) + labs(x="Horsepower")
|
|
#adjust axis limits and breaks
|
|
p2 + scale_x_continuous("Horsepower",
|
|
limits=c(0,400), breaks=seq(0, 400, 50))
|
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.