Cheatography
https://cheatography.com
First published by Slawa Rokicki on the "R for Public Health"-blog at http://rforpublichealth.blogspot.dk
Intro to ggplot2
The graphics package ggplot2 is powerful, aesthetically pleasing, and easy to use. The way ggplot2 works is by layering components of your plot on top of each other. You start a basic dataframe including x and y variables and then plot on top the customized layers. |
Basic scatterplots
library(ggplot2) |
library(gridExtra) |
mtc <- mtcars |
# Basic scatterplot |
p1 <- ggplot(mtc, aes(x = hp, y = mpg)) |
# Print plot with default points |
p1 + geom_point() |
Change color of points
#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))) |
Change shape or size of points
#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))) |
|
|
Example - change color of points
Example - change size of points
|
|
Example - add lines to a scatterplot
Add lines to scatterplot
#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") |
Change axis labels
#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)) |
|
Created By
Metadata
Favourited By
Comments
DaveChild, 22:36 20 Mar 14
Great cheat sheet!
Add a Comment
Related Cheat Sheets