Ggplot2 Cheatsheet 2.1 PDF
Ggplot2 Cheatsheet 2.1 PDF
ymin,
b + geom_freqpoly(aes(y = ..density..))
alpha, color, fill,linetype,
linetype, size size x, y, alpha,
x, y, alpha,
Continuous color, linetype, size
color, fill, Function
linetype, size
4 4
0
30
0
30
a + geom_histogram(binwidth = 5)
ymax, alpha, color,
x, y, alpha, color, linetype, size, weight g <- ggplot(economics, aes(date, unemploy))
i + geom_line()
1 1
a + geom_freqpoly()
2 3 4 2 3 4
+ 2
= 2 x, alpha, color, fill, linetype, size, weightLine
Discrete Segments Visualizing error= "hv") x, y, alpha, color, group, linetype, size
F MA 1
4
1
4
a <- ggplot(mpg, aes(fl)) f + geom_text(aes(label = cty))
common aesthetics: x, y, alpha,
x, y, color, linetype,
label, alpha, angle, color,size
family, fontface,
AeB<- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se)) = TRUE)
nudge_y
df <- data.frame(grp
x, y, alpha, =
= c("A",
color, 1, check_overlap
"B"), fit
linetype, = 4:5, se = 1:2)
size
Discrete X, Continuous Y x, y, label, alpha, angle, color, family, fontface,
0
b + geom_bar()
0
30 1 3 4 30 1 3 4
hjust, lineheight,aes(class,
size, vjust hwy))
Graphical
color, fill,Primitives
2 2
data geom coordinate plot g <- ggplot(mpg,
x=F + 2
system = 2 x, alpha,
b + geom_abline(aes(intercept=0, slope=1))
linetype, size, weight Visualizing error= 2)
e + hjust, lineheight, size, vjust
geom_crossbar(fatten
df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
Visualizing error
y=A 1 1
g + geom_bar(stat = "identity") x, y, ymax, ymin, alpha, color, fill, linetype, df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
color = F
size = A 0 0
c <- ggplot(map, aes(long, b + geom_hline(
lat)) aes(yintercept
x,Discrete X,=Continuous
y, alpha, color, lat)
fill, ) size,Y weight
linetype,
e <- ggplot(df,
size aes(grp, fit, ymin = fit-se, ymax = fit+se))
j <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))
0 1 3 4 0 1 3 4
Graphical Primitives= group))
2 2
data geom coordinate g <- ggplot(mpg, aes(class, hwy)) e + geom_errorbar()
x=F system
plot c + geom_polygon(aes(group
b + geom_vline(
x, y, alpha, color, fill, linetype, size
aes(xintercept
g + geom_boxplot()
= long) ) e + Discrete X, Continuous
geom_crossbar(fatten = 2)
x, ymax, ymin, alpha, color, linetype, size,
Y
y=A
color = F
b + geom_segment( g + geom_bar(stat = "identity")
aes(yend=lat+1,
lower, middle, xend=long+1))
upper, x, ymax, ymin, alpha, fwidth
x,<- ggplot(mpg,
y, ymax,
(also ymin,
geom_errorbarh())aes(class,
alpha, color, fill, linetype, hwy))
size = A c <- ggplot(map, aes(long, lat)) x, y, alpha,
color, color, fill,
fill, linetype, linetype,
shape, size, size,
weightweight size
e + geom_linerange() j + geom_crossbar(fatten = 2)
Complete the template below to build a graph. b + geom_spoke(
c + geom_polygon(aes(group aes(angle =g1:1155,
= group)) radius
+ geom_dotplot(binaxis = 1))= "y", e + geom_errorbar()
x, ymin, ymax, alpha, color, linetype, size x, y, ymax, ymin, alpha, color, fill, group,
g <- ggplot(economics, aes(date,
x, y, alpha, color, fill, linetype,unemploy))
size g + geom_boxplot() f + geom_col()
x, ymax, ymin, alpha, color, linetype, size,
stackdir = "center")
lower, middle, upper, x, ymax, ymin, alpha, width (also geom_errorbarh())
e + geom_pointrange() linetype, size
g + geom_path(lineend="butt",
Required
x, y, alpha, color, fill
e +x,geom_linerange()
y, alpha, color, fill, group, linetype, size
One Variable
color, fill, linetype, shape, size, weight
<DATA> >) +
ggplot(data = <DATA linejoin="round, linemitre=1) gg++geom_violin(scale
geom_dotplot(binaxis = "area")
= "y",
x, y, ymin, ymax, alpha, color, fill, linetype,
x, ymin,size
shape, ymax, alpha, color, linetype, size j + geom_errorbar()
x, y, alpha, color, linetype,
g <- ggplot(economics, aes(date,size unemploy)) x, y, alpha, color, fill, linetype, size, weight
<GEOM_FUNCTION>
<GEOM_FUNCTION> ( gg++geom_ribbon(
stackdir = "center")
fe ++ geom_pointrange()
geom_boxplot() x, ymax, ymin, alpha, color, group, linetype,
F MA 4 4
ymax=unemploy + 900))
aes(ymin=unemploy - 900,
geom_path(lineend="butt", Continuous x, y, alpha, color, fill Maps
size, width (also geom_errorbarh())
mapping = aes(<MAPPINGS> <MAPPINGS>3 ), linejoin="round , linemitre=1) data <-x,data.frame(murder = USArrests$Murder,
g + geom_violin(scale = "area") x, y, lower, middle,
y, ymin, ymax, alpha,
upper, ymax, ymin, alpha,
color, fill, linetype,
3
+
2 2
= x, ymax, ymin, c <-linetype,
alpha,
x, y, alpha, color, ggplot(mpg,
color, fill,
size
linetype, aes(hwy)); x,c2
size <- ggplot(mpg)
Discrete
y, alpha,
X, Discrete
color, fill, linetype,
Ysize, weight state
map <-
= tolower(rownames(USArrests)))
shape, size
map_data("state") j + geom_linerange()
stat = <STAT>
F MA
<STAT> 1, 1
Not g + geom_ribbon(aes(ymin=unemploy - 900, h <- ggplot(diamonds, aes(cut, color)) color, fill,
e <- ggplot(data, aes(fill group,
= murder)) linetype, shape, size, weight
4 4
3 required, =clong,
Maps x, ymin, ymax, alpha, color, group, linetype, size
position = <POSITION> <POSITION> d<-ymax=unemploy + 900) )
+fill,geom_area(stat h=+ "bin") e
fexpand_limits(
+
+= geom_dotplot(binaxis
geom_map( )+
= "y",
0 0
30 1 2 3 4 30 1 2 4 ggplot(seals, aes(x y = lat)) geom_jitter() data <- aes(map_id
data.frame(murder = = state), map =
USArrests$Murder, map
data geom 2 coordinate plot x, ymax, ymin, alpha, color, linetype, size state tolower(rownames(USArrests)))
x = map$long, y = map$lat)
) + + system
2
=
sensible d + geom_segment(aes( x, y, alpha, color, fill,h linetype, x, y,Discrete
alpha, X,fill,
color, Discrete
shape, Y
size
size aes(cut, color)) map <-
stackdir
map_data("state")
= "center") j + geom_pointrange()
x = F
y=A <- ggplot(diamonds, map_id, alpha, color, fill, linetype, size
1 1
xend = long + delta_long, e <- ggplot(data, aes(fill = murder))
<COORDINATE_FUNCTION>
<COORDINATE_FUNCTION> + 4 0 0 1 2 3 defaults e + x, y, alpha,
geom_map( color,= state),fill, map
group= map) +
yend = lat + delta_lat)) x, y, ymin, ymax, alpha, color, fill, group,
0
d<- ggplot(seals, aes(x = long, y = lat)) h + geom_jitter() aes(map_id
Three Variables
c + geom_density(kernel = "gaussian")
0 1 2 3 4
RStudio is a trademark of RStudio, Inc. CC BY RStudio info@rstudio.com 844-448-1212 rstudio.com Learn more at docs.ggplot2.org and www.ggplot2-exts.org ggplot2 2.1.0 Updated: 11/16
Stats - An alternative way to build a layer Scales Coordinate Systems Faceting
Scales map data values to the visual values of an r <- d + geom_bar() Facets divide a plot into subplots based on the values
A stat builds new variables to plot (e.g., count, prop).
fl cty cyl 4 4
aesthetic. To change a mapping, add a new scale. r + coord_cartesian(xlim = c(0, 5)) of one or more discrete variables.
x ..count..
3 3 xlim, ylim t <- ggplot(mpg, aes(cty, hwy)) + geom_point()
+ 2
= 2 (n <- d + geom_bar(aes(fill = fl))) The default cartesian coordinate system
t + facet_grid(. ~ fl)
1 1
0
0 1 2 3 4
0
0 1 2 3 4
scale_
aesthetic prepackaged scale specific r + coord_fixed(ratio = 1/2) facet into columns based on fl
data stat geom coordinate plot to adjust scale to use arguments
x=x system ratio, xlim, ylim
y = ..count..
t + facet_grid(year ~ .)
n + scale_fill_manual( Cartesian coordinates with fixed aspect
Visualize a stat by changing the default stat of a geom facet into rows based on year
function, geom_bar(stat="count") or by using a stat values = c("skyblue", "royalblue", "blue", "navy"), ratio between x and y units
limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", "r"), t + facet_grid(year ~ fl)
function, stat_count(geom="bar"), which calls a default r + coord_flip() facet into both rows and columns
name = "fuel", labels = c("D", "E", "P", "R"))
geom to make a layer (equivalent to a geom function). xlim, ylim t + facet_wrap(~ fl)
Use ..name.. syntax to map stat variables to aesthetics.
range of values to title to use in labels to use in breaks to use in Flipped Cartesian coordinates wrap facets into a rectangular layout
include in mapping legend/axis legend/axis legend/axis
r + coord_polar(theta = "x", direction=1 )
geom to use stat function geom mappings Set scales to let axis limits vary across facets
theta, start, direction
General Purpose scales t + facet_grid(drv ~ fl, scales = "free")
i + stat_density2d(aes(fill = ..level..), Use with most aesthetics Polar coordinates
geom = "polygon") variable created by stat r + coord_trans(ytrans = "sqrt") x and y axis limits adjust to individual facets
scale_*_continuous() - map cont values to visual ones "free_x" - x axis limits adjust
xtrans, ytrans, limx, limy
1D distributions scale_*_discrete() - map discrete values to visual ones "free_y" - y axis limits adjust
c + stat_bin(binwidth = 1, origin = 10) Transformed cartesian coordinates. Set
scale_*_identity() - use data values as visual ones xtrans and ytrans to the name
x, y | ..count.., ..ncount.., ..density.., ..ndensity.. Set labeller to adjust facet labels
c + stat_count(width = 1) x, y, | ..count.., ..prop.. scale_*_manual(values = c()) - map discrete values to of a window function.
manually chosen visual ones t + facet_grid(. ~ fl, labeller = label_both)
c + stat_density(adjust = 1, kernel = "gaussian") + coord_quickmap() 60
lat
orientation=c(41, -74, 0)) t + facet_grid(fl ~ ., labeller = label_bquote(alpha ^ .(fl)))
scale_*_datetime() - treat data x values as date times. c d e p r
e + stat_bin_2d(bins = 30, drop = T) 2D distributions projection, orientation, xlim, ylim
Use same arguments as scale_x_date(). long
t + facet_grid(. ~ fl, labeller = label_parsed)
x, y, fill | ..count.., ..density.. See ?strptime for label formats. Map projections from the mapproj package
(mercator (default), azequalarea, lagrange, etc.) c d e p r
e + stat_bin_hex(bins=30) x, y, fill | ..count.., ..density..
e + stat_density_2d(contour = TRUE, n = 100) X and Y location scales
Use with x or y aesthetics (x shown here) Position Adjustments Labels
x, y, color, size | ..level..
scale_x_log10() - Plot x on log10 scale Position adjustments determine how to arrange t + labs( x = "New x axis label", y = "New y axis label",
e + stat_ellipse(level = 0.95, segments = 51, type = "t")
scale_x_reverse() - Reverse direction of x axis geoms that would otherwise occupy the same space. title ="Add a title above the plot", Use scale
l + stat_contour(aes(z = z)) x, y, z, order | ..level.. scale_x_sqrt() - Plot x on square root scale s <- ggplot(mpg, aes(fl, fill = drv)) subtitle = "Add a subtitle below title", functions
to update
l + stat_summary_hex(aes(z = z), bins = 30, fun = max) s + geom_bar(position = "dodge") caption = "Add a caption below plot", legend labels
Color and fill scales (Discrete) Arrange elements side by side <aes>
<AES> = "New <aes>
<AES> legend title")
x, y, z, fill | ..value.. n <- d + geom_bar(aes(fill = fl))
l + stat_summary_2d(aes(z = z), bins = 30, fun = mean) s + geom_bar(position = "fill") t + annotate(geom = "text", x = 8, y = 9, label = "A")
n + scale_fill_brewer(palette = "Blues") Stack elements on top of one another,
x, y, z, fill | ..value.. 3 Variables For palette choices: RColorBrewer::display.brewer.all()
normalize height geom to place manual values for geoms aesthetics
n + scale_fill_grey(start = 0.2, end = 0.8, na.value e + geom_point(position = "jitter")
f + stat_boxplot(coef = 1.5) Comparisons = "red")
x, y | ..lower.., ..middle.., ..upper.., ..width.. , ..ymin.., ..ymax..
Add random noise to X and Y position of each Legends
element to avoid overplotting
f + stat_ydensity(kernel = "gaussian", scale = "area") Color and fill scales (Continuous) A
n + theme(legend.position = "bottom")
e + geom_label(position = "nudge")
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width.. o <- c + geom_dotplot(aes(fill = ..x..)) B
Place legend at "bottom", "top", "left", or "right"
Nudge labels away from points
o + scale_fill_distiller(palette = "Blues")
s + geom_bar(position = "stack") n + guides(fill = "none")
e + stat_ecdf(n = 40) x, y | ..x.., ..y.. Functions
o + scale_fill_gradient(low="red", high="yellow") Stack elements on top of one another Set legend type for each aesthetic: colorbar, legend,
e + stat_quantile(quantiles = c(0.1, 0.9), or none (no legend)
formula = y ~ log(x), method = "rq") x, y | ..quantile.. Each position adjustment can be recast as a function
o + scale_fill_gradient2(low="red", high="blue", n + scale_fill_discrete(name = "Title",
e + stat_smooth(method = "lm", formula = y ~ x, mid = "white", midpoint = 25) with manual width and height arguments
labels = c("A", "B", "C", "D", "E"))
se=T, level=0.95) x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. o + scale_fill_gradientn(colours=topo.colors(6)) s + geom_bar(position = position_dodge(width = 1)) Set legend title and labels with a scale function.
Also: rainbow(), heat.colors(), terrain.colors(),
cm.colors(), RColorBrewer::brewer.pal()
ggplot() + stat_function(aes(x = -3:3), n = 99, Themes Zooming
fun = dnorm, args = list(sd=0.5)) x | ..x.., ..y.. Shape and size scales Without clipping (preferred)
r + theme_bw() r + theme_classic()
150
t + coord_cartesian(
count
100
count
r + theme_light()
50 50
r + theme_gray()
150
100
r + theme_minimal()
count
50
0:1
Grey background
50
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Minimal themes
0
e + stat_summary(fun.data = "mean_cl_boot")
0
fl
(default theme)
c d e p r
fl
150
r + theme_dark()
count
50
General Purpose
c d e p r
fl
RStudio is a trademark of RStudio, Inc. CC BY RStudio info@rstudio.com 844-448-1212 rstudio.com Learn more at docs.ggplot2.org and www.ggplot2-exts.org ggplot2 2.1.0 Updated: 11/16
c(-1, 26)