Geoms - Use a geom to represent data points, use the geom’s aesthetic properties to represent variables. Each function returns a layer.

Data Visualization

Graphical Primitives

with ggplot2

Two Variables

a <- ggplot(seals, aes(x = long, y = lat))b <- ggplot(economics, aes(date, unemploy))

Cheat SheetA C e + geom_label(aes(label = cty), nudge_x = 1,
nudge_y = 1, check_overlap = TRUE)
B
Geoms(Useful- Use a geom
to represent data
points, use the geom’s aesthetic properties
to represent variables
for expanding
limits)x, y, label, alpha, angle, color, family, fontface,
One Variable
Two Variables hjust, lineheight, size, vjust

with ggplot2

with ggplot2

a + geom_curve(aes(yend = lat + delta_lat,

Continuous X, Continuous Y
Continuous
Bivariate Distribution= 2, width = 2)
erepresent+ggplot(movies,
geom_jitter(height
Geomsxend- Use=a geom
data
points,use thegeom’saesthetic properties tovariables
longto+representdelta_long,curvature=hwy))z))h <aes(year, rating))
f <- ggplot(mpg,aes(cty,

3

+
F MA

Basics=2y, alpha, color, fill,size
x, xend, y, yend, alpha,color, curvature, Two Variablesh +x,geom_bin2d(binwidth= c(5,shape,
0.5))
f + angle,
geom_blank()
One Variable
a + geom_area(stat= "bin")linetype,size
xmax, xmin, ymax, ymin, alpha, color, fill,
Continuous X, Continuous Y
Continuous Bivariate Distributionx, y, alpha, Continuouscolor, fill, linetype, size

1
0

4
1

b + geom_density(aes(y = ..county..))a + geom_freqpoly()
a+ geom_dotplot()

linetype, size, weight

xmax, xmin, ymax, ymin, alpha, color, fill,

size, weighth +linetype,
geom_hex()
ehx,++y,geom_density2d()geom_quantile()alpha,
colour, fill size
x, y, alpha, colour, linetype, size

x,Continuousy, alpha, color,group, linetype, size, weight
Functionh + geom_hex() aes(date, unemploy))g <- ggplot(economics,

4
0
3

f x,
+ geom_point()y, alpha, color, linetype, size, weightx, y, alpha, color, fill, group,
linetype,
sizesizex, y, alpha,color, fill, shape,x, y, alpha, color, linetype, size
x, y, alpha, color, fillb + geom_freqpoly(aes(y = ..density..))

1
0

0
3

geom_point()
he<-+ggplot(movies,
aes(year, rating))
h + geom_density2d()
hx,+x,
geom_bin2d(binwidth= c(5,0.5)) size, strokey, alpha,
shape,y, alpha,colour, color,
linetype, fill,size

b + geom_polygon(aes(group= group))f + geom_quantile()

2

1

3

4

y, alpha, colour, fill size
ge+x,+
geom_area()geom_rug(sides = "bl")f + geom_rug(sides = "bl")a + geom_rect(aes(xmin=color,long,
ymin
f alpha,+ geom_quantile()
linetype,
size = lat,a + geom_histogram(binwidth = 5)

geom
x=F
y=A

+

2

2

3

4

coordinate
system

1

=

+

=

+

=

2

2

plot

+

h + geom_hex()

x, y, alpha, colour, fill, size

Continuous Functioni <- ggplot(economics, aes(date, unemploy))i + geom_area()i + geom_line()x, y, alpha, color, group, linetype, size

1

AB

C

=

=

set of aesthetic mappings, and a default statand position adjustment.

linetype, size

RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com

aesthetic mappings

x, y, alpha, colour, group, linetype, size

x, y, alpha, color, fill, linetype, size

Functionx, Continuousy, alpha, color,
linetype, size

One Variable+

h + geom_density2d()x, y, alpha, color, fill, linetype, sizeg <- ggplot(economics, aes(date, unemploy))x, y,ymaxalpha, color,size, weightg + geom_line()
ax,+y,geom_freqpoly()
xmax=
long + delta_long,= latlinetype,+ delta_lat))alpha, color, fill, linetype,size, weightf + geom_smooth(model = lm)
gx,+y,geom_area()alpha, color, linetype, sizex,y,alpha,
color,
linetype,
size
xmax,
xmin,
ymax,
ymin,
alpha,
color,
fill,
linetype,size
b + geom_histogram(aes(y = ..density..))f x,+ geom_rug(sides= "bl") size, weight
e x,+y,geom_smooth(method= lm)y, alpha, color, fill, linetype,alpha, color, fill, linetype, sizeb + geom_freqpoly(aes(y = ..density..))00alpha,
color,
linetype,
size
Discrete
1
0
1
0
3
4
3
4
g + x,
geom_step(direction
=
"hv")
2
2 variables
To display data
values,
map
in
the
data
set
a + geom_histogram(binwidth=5)y, alpha, color, fill, group, linetype, size, weightbaes(fl))+ geom_ribbon(
aes(ymin=unemploy- 900,
data geom coordinateplot
f + geom_text(aes(label = cty))
gx,+y,geom_line()alpha, color, linetype, size<- ggplot(mpg,
4x, y,aalpha,color, fill, linetype,size, weightF M
A x = F 4 ofsystem
to aesthetic
properties
the geom
like size, color,f x,+ )geom_smooth(model= lm)y, label, alpha, angle, color,
family, fontface,
y=A
x,
y,
alpha, color, linetype, size
ymax=unemploy
+
900)
3
3
+ geom_histogram(aes(y = ..density..))b +bgeom_bar()
hjust,
lineheight,
vjust size, weightx, y, alpha,color,size,
fill, linetype,and x and y locations.2e+geom_text(aes(label= cty), nudge_x = 1,
Visualizing error
x,
ymax,
ymin,
alpha,
color,
fill,group,
linetype,size
2x, alpha, color,fill,linetype,
size,
weightDiscreteg + geom_step(direction= "hv")
df <- data.frame(grp= c("A", "B"), fit= 4:5, se = 1:2)
1
1
f + geom_text(aes(label = cty))
nudge_y=1,
check_overlapx,y,alpha,
color,
linetype,sizea<ggplot(mpg,aes(fl))e <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se)) = TRUE)
F MA
04
04
a + geom_segment(aes(yend=lat+ delta_lat,
Discrete
X, ContinuousYx, y, label, alpha,angle,
color, family,
fontface,
1
0
1
0
3
4
3
4
2
2
3
x, y, label, alpha, angle, color, family, fontface,3b+geom_bar()g <ggplot(mpg,
Graphical Primitives
hjust,
lineheight,aes(class,size, vjust hwy))
data geom coordinateplot
xend = long + delta_long))e + geom_crossbar(fatten
2)
Visualizing
error=size,
22x, alpha, color, fill, linetype, size, weightsystemx=F
hjust,
lineheight,
vjust
y=A
df <- data.frame(grp= c("A","B"),
fit =fill,4:5,
se = 1:2)
x, y, ymax, ymin,alpha,
color,
linetype,
1g +color,
geom_bar(stat= "identity")
x,
xend,
y,
yend,
alpha,
linetype,
size
color = F 1
sizec<ggplot(map,aes(long,lat))size = Ae<ggplot(df,aes(grp,
fit,
ymin
=
fit-se,ymax= fit+se))00x,Discretey, alpha, color,
fill, linetype, size,
weightX,
Continuous
Y
1
0
1
0
3
4
3
4
2
2
e + geom_errorbar()c+geom_polygon(aes(group=
group))
g<ggplot(mpg,aes(class,hwy))
Graphical
Primitives
data geom coordinateplot
a + geom_spoke(aes(yend= lat + delta_lat,
DiscreteY
ex,+ymax,geom_crossbar(fatten= 2)ymin, alpha,X,
color,Continuous
linetype,size,
g + geom_boxplot()x, y, alpha, color, fill, linetype, size
systemx=F
y=A(also ymin,
geom_errorbarh())
x,<y, ymax,alpha, color,
fill, linetype,xend = long + delta_long))
glower,+ geom_bar(statfwidth
ggplot(mpg,aes(class,hwy))
middle, upper,=x,"identity")
ymax, ymin, alpha,color = Fc <- ggplot(map, aes(long, lat))size = Ae +sizegeom_linerange()color,
fill, linetype,
shape,
size,
weightx, y,color,alpha,
color,
fill,
linetype,
size,
weightx, y, angle, radius, alpha,linetype,
size
ex,+ymin,geom_errorbar()ymax, alpha, color, linetype, sizec + geom_polygon(aes(group = group))g + geom_dotplot(binaxis = "y",g <- ggplot(economics, aes(date, unemploy))f +x, ymax,
geom_bar(stat= "identity")
ymin, alpha, color, linetype,size,
gstackdir+ geom_boxplot()
Build a graph with ggplot() or qplot()x, y, alpha, color, fill, linetype, size
= "center")(also geom_errorbarh())
e +widthgeom_pointrange()x,lower,y, alpha,color,upper,
fill x, ymax, ymin, alpha,g + geom_path(lineend="butt",middle,y, alpha,color,
linetype, size, weightex,+x,
fill, linetype, shape,size, weighty,geom_linerange()ymin,ymax, alpha,color,fill,
fill, linetype,linejoin="round’, linemitre=1)
g +color,
geom_violin(scale= "area")
ggplot(data = mpg, aes(x = cty, y = hwy))
shape,
x, ymin,size
ymax, alpha, color, linetype, size
x, y, alpha, color, linetype, size
gx,+y,geom_dotplot(binaxis=size,"y", weightalpha,
color,
fill,
linetype,g <- ggplot(economics, aes(date, unemploy))44geom_ribbon(aes(ymin=unemploy - 900,
F M
A you finish
stackdir = "center")
Maps
Begins a plotthatby addinglayers to. No gg+ymax=unemploy
f +geom_pointrange()
geom_boxplot()
Continuous
x, y, alpha, color, fill
+ 900))+ geom_path(lineend="butt",3
3
data e<-+data.frame(murder= USArrests$Murder,
defaults, but provides more
control2 than qplot().
x,linejoin="round’ymax, ymin, alpha,color, fill, linetype, sizeymin,ymax, alpha,color, fill,
linetype,ymax, ymin, alpha,, linemitre=1)
statex,=x,y,tolower(rownames(USArrests)))gaes(hwy))+ geom_violin(scale= "area")2y,lower,
middle,upper,
Discrete X, DiscreteYc<ggplot(mpg,
map<map_data("state")shape,
size
x, y, alpha, color, linetype, size
1y, alpha, color, fill, linetype,weight1
h <-x,ggplot(diamonds,
aes(cut, size,
color))
color,
fill,group,
linetype,
shape, size, weight
e <- ggplot(data,aes(fill= murder))dataF M Ag + geom_ribbon(aes(ymin=unemploy - 900,
04
04
add
layers, d<Maps = state), map = map) +e + geom_map(aes(map_idc+geom_area(stat="bin")
1
0
1
0
3
4
3
4
2
2
ggplot(seals,
aes(x
=
long,
y
=
lat))
h
+
geom_jitter()ymax=unemploy
+
900)
)
3
dataf<-+data.frame(murder= USArrests$Murder, = "y",geom_dotplot(binaxis
elements with + x, ymax, ymin, alpha, color, fill, linetype, size
data geom 3 coordinate
plot
expand_limits(
x = map$long, y = map$lat)state= tolower(rownames(USArrests)))
x, y,Discretealpha, color,shape, size
ggplot(mpg, aes(hwy,
cty))
2
x=F
X,fill,DiscreteYsystem + 2
size
d + geom_segment(aes( x, y, alpha, color, fill, linetype,alpha, color, fill, linetype, size
mapmap_id,<-stackdir
map_data("state")
y=A= "center")1h <- ggplot(diamonds, aes(cut, color))
geom_point(aes(color= cyl)) 1 +layer = geom + xend = long + delta_long,e <- ggplot(data, aes(fill = murder))= lat + delta_lat)) a + geom_area(aes(y = ..density..), stat = "bin")stat + d<-yend
geom_smooth(method 0 ="lm")+ 0 0 1 2 defaultx,y,alpha,
color,= state),
fill, map
groupe+geom_map(aes(map_id= map) +Three
Variables
1
0
3
4
3
4
2
ggplot(seals, aes(x = long, y = lat))h + geom_jitter()data geom + coordinate
plotlayer specific x, xend, y, yend, alpha, color, linetype, size
coord_cartesian()
expand_limits(
x = map$long, y = map$lat)
x, y, alpha, color,
fill, shape, size+ delta_lat^2))i+geom_raster(aes(fill=z),
hjust=0.5,
seals$z <- with(seals,sqrt(delta_long^2
f+geom_violin(scale="area")
x=F
systemgeom_segment(aes(mappings dd++geom_rect(aes(xminc =+long,
geom_density(kernel= "gaussian")
map_id, alpha, color, fill, linetype, size
ymin = lat,y=A
scale_color_gradient()+i <- ggplot(seals, aes(long, lat))vjust=0.5, interpolate=FALSE)
xend =long
long++delta_long,delta_long,xmax=
x, y, alpha, color, fill, group, linetype, size,
theme_bw()
yend == latlat ++ delta_lat))delta_lat)) x, y, alpha, color, fill, group, linetype, size, weight
additional ymax
Three Variables x, y, alpha, filli + geom_contour(aes(z = z))weightelementsi+geom_tile(aes(fill = z))
x,
xend,
y,
yend,
alpha,
color,
linetype,size
xmax, xmin, ymax, ymin, alpha, color, fill,
i +x, geom_raster(aes(fill= z),size
hjust=0.5,
seals$z <-x,with(seals,+ delta_lat^2))y, z, alpha, sqrt(delta_long^2
colour, linetype, size,
weighty, alpha, color, fill, linetype,size
dlinetype,+ geom_rect(aes(xmin= long,ymin = lat,c+geom_dotplot()i <- ggplot(seals, aes(long, lat))vjust=0.5, interpolate=FALSE)
Add a new layer to a plot with a geom_*()xmax= long + delta_long,x, y, alpha, fill
= lat + delta_lat)) x, y, alpha, color, fill
RStudio® is a function.
trademark of RStudio,
Inc. • provides
CC BY RStudio • info@rstudio.com• rstudio.com
Learn more at docs.ggplot2.org• ggplot2• Updated: 3/15Y
Discrete
X, 0.9.3.1
Discreteor stat_*()Eacha geom, a• 844-448-1212ymax
i + geom_contour(aes(z = z))
i + geom_tile(aes(fill = z))xmax, xmin, ymax, ymin, alpha, color, fill,

data

x, y, alpha, color, fill, linetype, size, weighta <- ggplot(mpg, aes(hwy))

43

h + geom_bin2d(binwidth = c(0.25, 500))

Continuous

ggplot2 is based on thegrammarf <- ggplot(mpg, aes(cty, hwy))
Cheat
Sheet of graphics, the b + geom_area(aes(y= ..density..),stat = "bin")a <- ggplot(mpg,aes(hwy))f + geom_jitter()b += "gaussian")
geom_path(lineend="butt",idea that you can build every graph from the same a + geom_density(kernalf x,+ geom_blank()y, alpha, color, fill, shape, sizea + geom_area(stat= "bin")linejoin="round’, linemitre=1)
color, fill, linetype,size, weight
Basicsfew components: a dataset, a set of geoms—visual x,x,y,y,alpha,alpha,
color,
fill,
linetype,size
b + geom_density(aes(y = ..county..))f + geom_point()
x, y, statalpha,+ geom_area(aes(y = ..density..),= "bin") color, group, linetype, size
marks that represent data points, and a coordinate a+bgeom_dotplot()f x,+ geom_jitter()y, alpha, color, fill, shape, size
ax,+y,geom_density(kernal="gaussian")x, y, alpha, color, fill, shape, sizealpha, color, fillsystem. F M A
x, y, alpha, color, fill, linetype, size, weight4

Continuous Bivariate Distribution
h <- ggplot(diamonds, aes(carat, price))a + geom_blank()

Data Visualization
Cheat Sheet
Data Visualization
BasicsContinuous X, Continuous Y
e <- ggplot(mpg, aes(cty, hwy))

data

geom

qplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point")
Creates a complete plot with given data, geom, andmappings. Supplies many useful defaults.

last_plot()
Returns the last plot

ggsave("plot.png", width = 5, height = 5)
Saves last plot as 5’ x 5’ file named "plot.png" inworking directory. Matches file type to file extension.

c + geom_freqpoly()x, y, z, alpha, colour, linetype, size, weightx, y, alpha, color, group, linetype, sizea + geom_freqpoly(aes(y = ..density..))g <-x, ggplot(diamonds,
y, alpha, color, fill, linetype, size aes(cut, color))g + geom_count()

Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15

x, y, alpha, color, fill, shape, size, strokec + geom_histogram(binwidth = 5)x, y, alpha, color, fill, linetype, size, weighta + geom_histogram(aes(y = ..density..))Discreted <- ggplot(mpg, aes(fl))
d + geom_bar()x, alpha, color, fill, linetype, size, weight

RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com

i + geom_step(direction = "hv")x, y, alpha, color, group, linetype, size

Visualizing error

df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
j <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))j + geom_crossbar(fatten = 2)

x, y, ymax, ymin, alpha, color, fill, group,
linetype, sizej + geom_errorbar()x, ymax, ymin, alpha, color, group, linetype,size, width (also geom_errorbarh())

j + geom_linerange()x, ymin, ymax, alpha, color, group, linetype, sizej + geom_pointrange()x, y, ymin, ymax, alpha, color, fill, group,
linetype, shape, size

Mapsdata <- data.frame(murder = USArrests$Murder,
state = tolower(rownames(USArrests)))
map <- map_data("state")k <- ggplot(data, aes(fill = murder))k + geom_map(aes(map_id = state), map = map) +expand_limits(x = map$long, y = map$lat)
map_id, alpha, color, fill, linetype, size

Three Variables
seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))l <- ggplot(seals, aes(long, lat))l + geom_contour(aes(z = z))x, y, z, alpha, colour, group, linetype, size,
weightl + geom_raster(aes(fill = z), hjust=0.5,
vjust=0.5, interpolate=FALSE)
x, y, alpha, filll + geom_tile(aes(fill = z))x, y, alpha, color, fill, linetype, size, width

Learn more at docs.ggplot2.org • ggplot2 2.0.0 • Updated: 12/15

Stats - An alternative way to build a layer

ScalesSome plots visualize a transformation of the original data set.
Use a stat to choose a common transformation to visualize,
e.g. a + geom_bar(stat = "count")

Scales control how a plot maps data values to the visualvalues of an aesthetic. To change the mapping, add acustom scale.

1

stat

geom

1

scale_

0

0

data

2

0

1

2

3

4

coordinate
x=xsystemy = ..count..

0

1

2

plot

3

4

Each stat creates additional variables to map aesthetics
to. These variables use a common ..name.. syntax.
stat and geom functions both combine a stat with ageom to make a layer, i.e. stat_count(geom="bar")
does the same as geom_bar(stat="count")
stat function

layer mappingsi + stat_density2d(aes(fill = ..level..),geom = "polygon", n = 100) variable
geom for layer

parameters for stat

created bytransformationc + stat_bin(binwidth = 1, origin = 10)
1D distributions
x, y | ..count.., ..ncount.., ..density.., ..ndensity..
c + stat_count(width = 1)
x, y, | ..count.., ..prop..
c + stat_density(adjust = 1, kernel = "gaussian")x, y, | ..count.., ..density.., ..scaled..
e + stat_bin_2d(bins = 30, drop = TRUE)
2D distributions
x, y, fill | ..count.., ..density..
e + stat_bin_hex(bins = 30)
x, y, fill | ..count.., ..density..
e + stat_density_2d(contour = TRUE, n = 100)x, y, color, size | ..level..
e + stat_ellipse(level = 0.95, segments = 51, type = "t")l + stat_contour(aes(z = z))
3 Variables
x, y, z, order | ..level..
l + stat_summary_hex(aes(z = z), bins = 30, fun = mean)x, y, z, fill | ..value..
l + stat_summary_2d(aes(z = z), bins = 30, fun = mean)x, y, z, fill | ..value..
f + stat_boxplot(coef = 1.5)
Comparisonsx, y | ..lower.., ..middle.., ..upper.., ..width.. , ..ymin.., ..ymax..
f + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area")x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width..
e + stat_ecdf(n = 40)
Functionsx, y | ..x.., ..y..
e + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x),method = "rq")x, y | ..quantile..
e + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80,
fullrange = FALSE, level = 0.95)
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax..

ggplot() + stat_function(aes(x = -3:3),
General Purpose
fun = dnorm, n = 101, args = list(sd=0.5))
x | ..x.., ..y..
e + stat_identity(na.rm = TRUE)
ggplot() + stat_qq(aes(sample=1:100), distribution = qt,
dparams = list(df=5))
sample, x, y | ..sample.., ..theoretical..
e + stat_sum()x, y, size | ..n.., ..prop..
e + stat_summary(fun.data = "mean_cl_boot")h + stat_summary_bin(fun.y = "mean", geom = "bar")e + stat_unique()aesthetic prepackaged
to adjust scale to use

title to use inlegend/axislabels to use inlegend/axis

xlim, ylim
Flipped Cartesian coordinates

breaks to use inlegend/axis

r + coord_polar(theta = "x", direction=1 )theta, start, direction
Polar coordinates

Use with any aesthetic:alpha, color, fill, linetype, shape, sizer + coord_trans(ytrans = "sqrt")
xtrans, ytrans, limx, limy
Transformed cartesian coordinates. Set
xtrans and ytrans to the nameof a window function.

scale_*_continuous() - map cont’ values to visual values
scale_*_discrete() - map discrete values to visual values
scale_*_identity() - use data values as visual values
scale_*_manual(values = c()) - map discrete values tomanually chosen visual values

π + coord_map(projection = "ortho",orientation=c(41, -74, 0))60

Use with x or y aesthetics (x shown here)
scale_x_date(date_labels = "%m/%d"),date_breaks = "2 weeks") - treat x values as dates.
See ?strptime for label formats.
scale_x_datetime() - treat x values as date times. Usesame arguments as scale_x_date().
scale_x_log10() - Plot x on log10 scale
scale_x_reverse() - Reverse direction of x axis
scale_x_sqrt() - Plot x on square root scale

Position Adjustments
Position adjustments determine how to arrange
geoms that would otherwise occupy the same space.

s <- ggplot(mpg, aes(fl, fill = drv))
s + geom_bar(position = "dodge")
Arrange elements side by side

Color and fill scaless + geom_bar(position = "fill")Continuouso <- c + geom_dotplot(aes(fill = ..x..))n + scale_fill_brewer(
palette = "Blues")
For palette choices:
library(RColorBrewer)
display.brewer.all()o + scale_fill_gradient(
low = "red",high = "yellow")o + scale_fill_gradient2(
low = "red", high = "blue",mid = "white", midpoint = 25)

n + scale_fill_grey(
start = 0.2, end = 0.8,
na.value = "red")

Stack elements on top of one another,normalize height

e + geom_point(position = "jitter")AB

s + geom_bar(position = position_dodge(width = 1))

Manual Shape values

0

6

12

18

24

0

p + scale_shape(solid = FALSE)

1

7

13

19

25

+

2

8

14

20

*

-

3

9

15

21

.

10

5

11

16
17

22
23

0
+
* |
o %
O #

o

O

Themesr + theme_bw()

150

|

100

50

c

%

d

e

p

r

fl

r + theme_gray()

150

#

100

50

c

d

e

p

Grey background(default theme)rflSize scales

RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com

p + scale_size_area(
max_scale = 6)

Maps to area of circle (not radius)t + facet_grid(year ~ .)facet into rows based on yeart + facet_grid(year ~ fl)facet into both rows and columns

150

r + theme_dark()

100

50

0
c

d

e

fl

p

r

dark for contrast

100

50

0
c

d

e

p

r

fl

150

100

50

0
c

d

e

fl

p

r

t + facet_wrap(~ fl)wrap facets into a rectangular layout

Set scales to let axis limits vary across facetst + facet_grid(drv ~ fl, scales = "free")x and y axis limits adjust to individual facets• "free_x" - x axis limits adjust• "free_y" - y axis limits adjust

Set labeller to adjust facet labelst + facet_grid(. ~ fl, labeller = label_both)
fl: d

fl: e

fl: p

fl: r

t + facet_grid(fl ~ ., labeller = label_bquote(alpha ^ .(fl)))
↵c
↵e
↵p
↵r
↵d
t + facet_grid(. ~ fl, labeller = label_parsed)
c

d

e

p

r

Labelst + ggtitle("New Plot Title")

Add a main title above the plott + xlab("New X label")
Change the label on the X axist + ylab("New Y label")

Use scale functions
to update legend
labelsChange the label on the Y axist + labs(title =" New title", x = "New x", y = "New y")
All of the above

Legendsn + theme(legend.position = "bottom")Place legend at "bottom", "top", "left", or "right"

n + guides(fill = "none")Set legend type for each aesthetic: colorbar, legend,
or none (no legend)n + scale_fill_discrete(name = "Title",labels = c("A", "B", "C", "D", "E"))Set legend title and labels with a scale function.

Zoomingr + theme_classic()r + theme_light()
r + theme_linedraw()
r + theme_minimal()

150

White backgroundwith grid lines

00

p + scale_radius(
range=c(1,6))
p + scale_size()

Nudge labels away from points

Each position adjustment can be recast as a function
with manual width and height arguments

Manual shape values

4

e + geom_label(position = "nudge")

Stack elements on top of one anotherp <- e + geom_point(aes(shape = fl, size = cyl))p + scale_shape_manual(values = c(3:7))
Shape values shown inchart on right

Add random noise to X and Y position of eachelement to avoid overplottings + geom_bar(position = "stack")o + scale_fill_gradientn(
colours = terrain.colors(6))
Also: rainbow(), heat.colors(),
topo.colors(), cm.colors(),
RColorBrewer::brewer.pal()

Shape scales

facet into columns based on fl

fl: cprojection, orientation, xlim, ylim
Map projections from the mapproj package long(mercator (default), azequalarea, lagrange, etc.)

X and Y location scalesn <- d + geom_bar(
aes(fill = fl))t + facet_grid(. ~ fl)r + coord_flip()

General Purpose scales

Discretet <- ggplot(mpg, aes(cty, hwy)) + geom_point()

ratio, xlim, ylim
Cartesian coordinates with fixed aspectratio between x and y unitsn + scale_fill_manual(values = c("skyblue", "royalblue", "blue", "navy"),
limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", "r"),name = "fuel", labels = c("D", "E", "P", "R"))
range of values toinclude in mapping

Facets divide a plot into subplots based on the valuesof one or more discrete variables.

r + coord_fixed(ratio = 1/2)

scale specificarguments

lat

=

2

n <- b + geom_bar(aes(fill = fl))
n

count

3

count

3

xlim, ylim
The default cartesian coordinate system

count

+

4

r + coord_cartesian(xlim = c(0, 5))count

x ..count..

r <- d + geom_bar()count

fl cty cyl

4Faceting

Coordinate Systems

Minimal themesr + theme_void()
Empty theme

Without clipping (preferred)t + coord_cartesian(
xlim = c(0, 100), ylim = c(10, 20))
With clipping (removes unseen data points)t + xlim(0, 100) + ylim(10, 20)
t + scale_x_continuous(limits = c(0, 100)) +scale_y_continuous(limits = c(0, 100))
Learn more at docs.ggplot2.org • ggplot2 2.0.0 • Updated: 12/15