ggplot2-scatterplots Cheat Sheet
by Jens Preußner (Jenzopr) via cheatography.com/18621/cs/1841/
Intro to ggplot2 Change shape or size of points (cont) Example - add lines to a scatterplot
The graphics package ggplot2 is powerful, p4 <- p1 + geom_point(aes(shape =
aesthetically pleasing, and easy to use. The factor(am)))
way ggplot2 works is by layering components of
More options:
your plot on top of each other. You start a basic
http://docs.ggplot2.org/0.9.3.1/scale_manual.html
dataframe including x and y variables and then
plot on top the customized layers.
Example - change color of points
Need help? Use
http://docs.ggplot2.org/0.9.2.1/index.html or
http://www.cookbook-r.com/Graphs as
references.
Basic scatterplots
library(ggplot2)
library(gridExtra)
Add lines to scatterplot
mtc <- mtcars
#connect points with line
# Basic scatterplot
p1 + geom_point(color="blue") + geom_line()
p1 <- ggplot(mtc, aes(x = hp, y = mpg))
#add regression line
# Print plot with default points
p1 + geom_point(color="red") +
p1 + geom_point()
geom_smooth(method = "lm", se = TRUE)
Example - change size of points
Change color of points #add vertical line
geom_point() + geom_vline(xintercept = 100,
#set one color for all points
color="red")
p1 + geom_point(color="red")
#set color scale by a continuous variable Change axis labels
p1 + geom_point(aes(color = wt)) #label all axes at once
#set color scale by a factor variable p2 + labs(x="Horsepower",
p1 + geom_point(aes(color=factor(am))) y = "Miles per Gallon")
#label and change font size
Change shape or size of points
p2 + theme(axis.title.x = element_text(face=
#increase all points to size 5
"bold", size=20)) + labs(x="Horsepower")
p2 <- p1 + geom_point(size = 5)
#adjust axis limits and breaks
#set point size by continuous variable
p2 + scale_x_continuous("Horsepower",
p3 <- p1 + geom_point(aes(size = wt)) Reference
limits=c(0,400), breaks=seq(0, 400, 50))
#set point shape by factor variable See
http://rforpublichealth.blogspot.dk/2013/11/ggplot2-
cheatsheet-for-scatterplots.html for the
complete cheat sheet by Slawa Rokicki.
By Jens Preußner (Jenzopr) Published 19th March, 2014. Sponsored by CrosswordCheats.com
cheatography.com/jenzopr/ Last updated 30th April, 2014. Learn to solve cryptic crosswords!
Page 1 of 1. http://crosswordcheats.com