You are on page 1of 2

Geoms

Data Visualization

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

One Variable

with ggplot2

Two Variables

Continuous

Cheat Sheet

Continuous X, Continuous Y
f <- ggplot(mpg, aes(cty, hwy))

a <- ggplot(mpg, aes(hwy))

with ggplot2

Cheat Sheet
Data Visualization
Basics

i + geom_bin2d(binwidth = c(5, 0.5))

f + geom_blank()

a + geom_area(stat = "bin")

Data Visualization

Continuous Bivariate Distribution


i <- ggplot(movies, aes(year, rating))
xmax, xmin, ymax, ymin, alpha, color, fill,
linetype, size, weight

Geomsx,-y,Usealpha,
a geomcolor,
to represent
data points,size
use the geoms aesthetic properties to represent variables
fill, linetype,
One Variableb + geom_area(aes(y = ..density..), stat = "bin")
Continuous
a+

i + geom_density2d()

Two Variables f + geom_jitter()

X, Continuous Y
Continuous Bivariate Distribution
= "gaussian")
Geoms geom_density(kernel
- Use a geom to represent Continuous
data
points,
use the
geoms
aesthetic properties to
represent
variables
x,
y, alpha,
color, fill,
shape, size
h <ggplot(movies,
aes(year,
rating))
f <- ggplot(mpg,
aes(cty,
hwy))

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


size, weight
f + geom_blank()
One Variable
Two Variablesh + geom_bin2d(binwidth = c(5, 0.5))
a + geom_area(stat
= "bin")
with ggplot2
xmin, ymax, ymin, alpha, color, fill,
b
+
geom_density(aes(y
=
..county..))
f xmax,
+ geom_point()
Continuous X, Continuous Y
Continuous
x, y, alpha, Continuous
color, fill, linetype, size
linetype, size,Bivariate
weight Distribution
ggplot2 is based on the
grammar
h <- ggplot(movies, aes(year, rating))
f <- ggplot(mpg, aes(cty, hwy))
Cheat
Sheet of graphics, the b + geom_area(aes(y
=
..density..),
stat
=
"bin")
a <- ggplot(mpg, aes(hwy))
a + geom_dotplot() f + geom_jitter()
h + x,
geom_density2d()
y,
alpha,
color, fill, shape, size
idea that you can build every graph from the same a + geom_density(kernal = "gaussian")
hx,+y,geom_bin2d(binwidth
= c(5, 0.5))
f x,
+ geom_blank()
alpha, colour, linetype, size
y, alpha, color, fill, shape, size
ax,+y,geom_area(stat
=
"bin")
x,
y,
alpha,
color,
fill
color, fill, linetype, size, weight
xmax, xmin, ymax, ymin, alpha, color, fill,
Basics
few components: a data
set, a set of geomsvisual x, y,alpha,
alpha, color, fill, linetype,
size
linetype,
size, weight
b + geom_density(aes(y
= ..county..))
hf ++
geom_hex()
f + geom_point()
geom_quantile()
+ geom_area(aes(y = ..density..), stat = "bin")
marks that represent data points, and a coordinate a+bgeom_dotplot()
hx,+y,geom_density2d()
f x,
+ geom_jitter()
alpha, colour, fill size
y, alpha, color, fill, shape, size
ax,+y,geom_density(kernal
=
"gaussian")
x,x,
y, y,
alpha,
colour, color,
linetype, size
alpha,
linetype, size, weight
alpha, color, fill a + geom_freqpoly() x, y, alpha, color, fill, shape, size
system. F M A
x, y, alpha, color, fill, linetype,
size, weight
Basics
Continuous Function
f + geom_quantile()
b + geom_density(aes(y =x,..county..))
h + geom_hex() aes(date, unemploy))
g <- ggplot(economics,
f x,
+ geom_point()
y, alpha, color, linetype,
sizecolor, linetype, size, weight
y, alpha,
a + geom_freqpoly()
a+ geom_dotplot()
x,geom_area()
y,geom_rug(sides
alpha, colour, fill size
x, y, alpha, color, fill, shape, size
f
= "bl")
+
=
g
++
x, y, alpha, color, linetype,b
size
+ geom_freqpoly(aes(y
= ..density..))
x, y, alpha, color, fill
f
+
geom_rug(sides
=
"bl")
x,alpha,
y, alpha, color,
fill, linetype,
size size
b + geom_freqpoly(aes(y = ..density..))
F MA
color,
linetype,
Continuous Function
f alpha,
+ geom_quantile()
color, linetype, size
4

a + geom_histogram(binwidth
= 5)
a + geom_histogram(binwidth
= 5)
g <- ggplot(economics, aes(date, unemploy))
x, y, alpha, color, linetype, size, weight
g + geom_line()
ax,+y,geom_freqpoly()
alpha, color, fill, linetype, size, weight
f
+
geom_smooth(model
= lm)
x,
y,
alpha,
color,
fill,
linetype,
size,
weight
+y,geom_area()
alpha, color, linetype, size
x,
y,
alpha,
color,
linetype,
size
1
1
b + geom_histogram(aes(y = ..density..))
fgx,+
geom_smooth(model
= lm)
f x,
+ geom_rug(sides
= "bl") size, weight
y, alpha, color, fill, linetype,
x, y, alpha, color, fill, linetype, size
b + geom_freqpoly(aes(yb
= ..density..))
0
0
+
geom_histogram(aes(y
=
..density..))
alpha,
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, linetype, size, weight
data geom coordinate
plot
f + geom_text(aes(label = cty))
gx,+y,geom_line()
alpha, color, linetype, size
<- ggplot(mpg,
aes(fl))size, weight
4
x, y,aalpha,
color, fill, linetype,
F M
A x = F 4 ofsystem
to aesthetic
properties
the geom
like size, color,
f x,
+ geom_smooth(model
= lm)
Discrete
y, label, alpha, angle, color,
family, fontface,
y=A
x,
y,
alpha, color, linetype, size
3
3
+ geom_histogram(aes(y = ..density..))
b +bgeom_bar()
hjust,
lineheight,
vjust size, weight
x, y, alpha,
color,size,
fill, linetype,
and x and y locations.2
f
+
geom_text(aes(label
= cty))
Visualizing error
2
x, alpha, color,
fill,
linetype,
size,
weight
b <- ggplot(mpg, aes(fl))
Discrete
g + 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))
x,
y,
label,
alpha,
angle,
color,
x,
y,
alpha,
color,
linetype,
size
a
<ggplot(mpg,
aes(fl))
e <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se)) family, fontface,
F MA
04
04
Discrete
X, Continuous
Y
x, y, label, alpha,
angle, color, family,
fontface,
b + geom_bar()
1
0
1
0
3
4
3
4
2
2
hjust, lineheight, size, vjust
3
3
b
+
geom_bar()
g <ggplot(mpg,
Graphical Primitives
hjust,
lineheight,aes(class,
size, vjust hwy))
data geom coordinate
plot
e + geom_crossbar(fatten
Visualizing error= 2)
2
2
x, alpha, color, fill, linetype,
size,
weightcolor, fill, linetype, size, weight
system
x=F
x,
alpha,
y=A
df <- data.frame(grp
= c("A",
"B"),
fit =fill,4:5,
se = 1:2)
x, y, ymax, ymin,
alpha,
color,
linetype,
1
g + geom_bar(stat = "identity")
color = F 1
size aes(grp, fit, ymin = fit-se, ymax = fit+se))
c <- ggplot(map, aes(long, lat))
size = A
e <- ggplot(df,
0
0
x,Discrete
y, alpha, color,
fill, linetype, size,
weight
X,
Continuous
Y
1
0
1
0
3
4
3
4
2
2
e + geom_errorbar()
c + geom_polygon(aes(group
g <- ggplot(mpg, aes(class, hwy))
Graphical Primitives= group))
data geom coordinate
plot
Discrete
Continuous
Y
ex,+ymax,
geom_crossbar(fatten
= 2)
ymin, alpha,X,
color,
linetype,
size,
g + geom_boxplot()
x, y, alpha, color, fill, linetype, size
system
x=F
y=A
(also
geom_errorbarh())
x, <y, ymax,
ymin,
alpha, color,aes(class,
fill, linetype,
gwidth
ggplot(mpg,
hwy))
glower,
+ geom_bar(stat
middle, upper,=x,"identity")
ymax, ymin, alpha,
color = F
c <- ggplot(map, aes(long, lat))
size = A
e +size
geom_linerange()
color,
fill, linetype,
shape,
size, size,
weight
x, y, alpha,
color, fill,
linetype,
weight
ex,+ymin,
geom_errorbar()
ymax, alpha, color, linetype, size
c + geom_polygon(aes(group = group))
g + geom_dotplot(binaxis = "y",
g <- ggplot(economics, aes(date, unemploy))
g x,+ymax,
geom_bar(stat
= "identity")
ymin, alpha, color, linetype,
size,
gstackdir
+ geom_boxplot()
Build a graph with qplot() or ggplot()
x, y, alpha, color, fill, linetype, size
= "center")
(also geom_errorbarh())
e +width
geom_pointrange()
x,lower,
y, alpha,
color,
fill x, ymax, ymin, alpha,
g + geom_path(lineend="butt",
c <- ggplot(map, aes(long,
lat))
middle,
upper,
y, alpha,
color,
linetype, size, weight
ex,+x,
fill, linetype, shape,
size, weight
y,geom_linerange()
ymin,
ymax, alpha,
color,fill,
fill, linetype,
linejoin="round, linemitre=1)
geom
aesthetic mappings
g +color,
geom_violin(scale
= "area")
data
shape,
x, ymin,size
ymax, alpha, color, linetype, size
c
+
geom_polygon(aes(group
=
group))
x, y, alpha, color, linetype,
size
gx,+y,geom_dotplot(binaxis
=size,
"y", weight
alpha,
color,
fill,
linetype,
g <- ggplot(economics, aes(date, unemploy))
qplot(x = cty,Fy M
= hwy,
A color4 = cyl, data = 4mpg, geom = "point"g) + geom_ribbon(aes(ymin=unemploy - 900,
stackdir = "center")
Maps
g +geom_pointrange()
geom_boxplot()
sizefill
x, y, alpha, color,
+ 900)) x, y, alpha, color, fill, linetype,
gymax=unemploy
+ geom_path(lineend="butt",
3
3
data e<-+data.frame(murder
= USArrests$Murder,
Creates a complete plot2 with given data,
geom,
and
x,linejoin="round
ymax, ymin, alpha,
color, fill, linetype, size
y,tolower(rownames(USArrests)))
ymin, ymax,
alpha, color,
fill, linetype,
, linemitre=1)
statex,=lower,
g + geom_violin(scale
= "area")
2
middle,
upper,
x, ymax, ymin, alpha,
Discrete X, Discrete
Y
map
<map_data("state")
shape,
size
x, y, alpha, color, linetype, size
mappings. Supplies many
useful defaults.
1
y, alpha, color, fill, linetype,
weight
1
h <-x,ggplot(diamonds,
aes(cut, size,
color))
e <- ggplot(data,
aes(fill
= murder)) shape, size, weight
color,
fill,
linetype,
g + geom_ribbon(aes(ymin=unemploy - 900,
F MA
04
04
Maps = state), map = map) +
e + geom_map(aes(map_id
1
0
1
0
3
4
3
4
2
2
d<-ymax=unemploy
ggplot(seals, aes(x
= long,
y = lat))
h + geom_jitter()
+ 900)
)
3
datag<-+
data.frame(murder
= USArrests$Murder, = "y",
geom_dotplot(binaxis
data geom 3 coordinate
plot
expand_limits(
x = map$long, y = map$lat)
x,
ymax,
ymin,
alpha,
color,
fill,
linetype,
size
state
=
tolower(rownames(USArrests)))
x,
y,
alpha,
color,
fill,
shape,
size
d <- ggplot(economics, aes(date,
unemploy))
2
2
=F
Discrete
X, Discrete Y
ggplot(data = mpg, xyaes(x
=system
cty, y = hwy))
d + geom_segment(aes(
alpha, color, fill, linetype, size
mapmap_id,
<-stackdir
map_data("state")
=A
= "center")
1
1
h <- ggplot(diamonds, aes(cut, color))
xend = long + delta_long,
e <- ggplot(data, aes(fill = murder))
Begins a plot that you finish
by3 adding
layers
to. No yend = lat + delta_lat))
0
0
x,
y,
alpha,
color,= state),
fill map = map) +
+ geom_path(lineend="butt",
e
+
geom_map(
aes(map_id
Three
Variables
1
0
1
0
3
4
4
2
2
d<- ggplot(seals, aes(x d
= long,
y = lat))
h + geom_jitter()
x, xend, y, yend, alpha, color, linetype, size
geom more
coordinate
plotqplot().
expand_limits(
x
=
map$long,
= map$lat)
defaults, butdata
provides
control
than
linejoin="round
, linemitre=1)
x, y, alpha, color,
fill, shape, size+ delta_lat^2))
++
geom_raster(aes(fill
= z),yhjust=0.5,
seals$z
<- with(seals,
sqrt(delta_long^2
gi map_id,
geom_violin(scale
= "area")
x=F
system
geom_segment(aes(= long, ymin = lat,
alpha, color, fill, linetype, size
dd++geom_rect(aes(xmin
y=A
i
<ggplot(seals,
aes(long,
lat))
vjust=0.5,
interpolate=FALSE)
data
xend =long
long++delta_long,
delta_long,
x,
y,
alpha,
color,
linetype,
size
xmax=
x, y, alpha, color, fill, linetype, size, weight
add layers, ymax
yend == lat
lat ++ delta_lat))
delta_lat))
Three Variables x, y, alpha, fill
i + geom_contour(aes(z = z))
elements with + xmax,
i
+
geom_tile(aes(fill = z))
x, xend,
y,
yend,
alpha,
color,
linetype,
size
d
+
geom_ribbon(
aes(ymin=unemploy
900,
xmin, ymax, ymin, alpha, color, fill,
ggplot(mpg, aes(hwy, cty)) +
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,
weight
y, alpha, color, fill, linetype,
linetype,
size
ymax=unemploy
+
900)
)
d
+
geom_rect(aes(xmin
=
long,
ymin
=
lat,
geom_point(aes(color = cyl)) +
layer = geom +
i <- ggplot(seals, aes(long, lat))
vjust=0.5, interpolate=FALSE)
long + delta_long,
x, ymax, ymin, alpha, color, fill, linetype, size
default stat + xmax=
geom_smooth(method
="lm") +
x, y, alpha, fill
ymax
= lat + delta_lat))
RStudio is a trademark of RStudio, Inc. CC BY RStudio info@rstudio.com 844-448-1212
rstudio.com
Learn more at docs.ggplot2.org
ggplot2
Updated: 3/15Y
Discrete
X, 0.9.3.1
Discrete
i + geom_contour(aes(z = z))
layer specific xmax,
i + geom_tile(aes(fill = z))
coord_cartesian() +
xmin, ymax, ymin, alpha, color, fill,
data

x=F
y=A

0
3

geom

i + geom_hex()
x, y, alpha, colour, fill size

Continuous Function
j <- ggplot(economics, aes(date, unemploy))
j + geom_area()
x, y, alpha, color, fill, linetype, size

1
0

x, y, alpha, colour, linetype, size

a <- ggplot(mpg, aes(hwy))

0
3

coordinate
system

plot

AB

Graphical Primitives

scale_color_gradient() +
theme_bw()

mappings

additional
elements

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

Add a new layer to a plot with a geom_*()


or stat_*() function. Each provides a geom, a
set of aesthetic mappings, and a default stat
and position adjustment.
last_plot()
Returns the last plot

ggsave("plot.png", width = 5, height = 5)


Saves last plot as 5 x 5 file named "plot.png" in
working directory. Matches file type to file extension.

x, y, z, alpha, colour, linetype, size, weight

linetype, size

e <- ggplot(seals, aes(x = long, y = lat))

e + geom_segment(aes(
xend = long + delta_long,
yend = lat + delta_lat))
x, xend, y, yend, alpha, color, linetype, size

e + geom_rect(aes(xmin = long, ymin = lat,


xmax= long + delta_long,
ymax = lat + delta_lat))
xmax, xmin, ymax, ymin, alpha, color, fill,
linetype, size

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

h <-x, ggplot(diamonds,
y, alpha, color, fill, linetype, size aes(cut, color))

j + geom_line()
x, y, alpha, color, linetype, size

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

Visualizing error

df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)


k <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))

k + geom_crossbar(fatten = 2)
x, y, ymax, ymin, alpha, color, fill, linetype,
size

k + geom_errorbar()
x, ymax, ymin, alpha, color, linetype, size,
width (also geom_errorbarh())

k + geom_linerange()
x, ymin, ymax, alpha, color, linetype, size

k + geom_pointrange()
x, y, ymin, ymax, alpha, color, fill, linetype,
shape, size

Maps

data <- data.frame(murder = USArrests$Murder,


state = tolower(rownames(USArrests)))
map <- map_data("state")
l <- ggplot(data, aes(fill = murder))

l + geom_map(aes(map_id = state), map = map) +


expand_limits(x = map$long, y = map$lat)

h + geom_jitter()

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

x, y, alpha, color, fill, shape, size

map_id, alpha, color, fill, linetype, size

Three Variables
seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))
m <- ggplot(seals, aes(long, lat))

m + geom_contour(aes(z = z))
x, y, z, alpha, colour, linetype, size, weight

m + geom_raster(aes(fill = z), hjust=0.5,


vjust=0.5, interpolate=FALSE)
x, y, alpha, fill

m + geom_tile(aes(fill = z))
x, y, alpha, color, fill, linetype, size
Learn more at docs.ggplot2.org ggplot2 0.9.3.1 Updated: 3/15

Stats - An alternative way to build a layer

Scales

Some 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 = "bin")

Scales control how a plot maps data values to the visual


values of an aesthetic. To change the mapping, add a
custom scale.

2
1

stat

geom

2
1

scale_

data

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


n

coordinate
x=x
system
y = ..count..

plot

Each stat creates additional variables to map aesthetics


to. These variables use a common ..name.. syntax.
stat functions and geom functions both combine a stat
with a geom to make a layer, i.e. stat_bin(geom="bar")
does the same as geom_bar(stat="bin")
stat function

layer specific
mappings

variable created
by transformation

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

parameters for stat

a + stat_bin(binwidth = 1, origin = 10)


1D distributions
x, y | ..count.., ..ncount.., ..density.., ..ndensity..
a + stat_bindot(binwidth = 1, binaxis = "x")
x, y, | ..count.., ..ncount..
a + stat_density(adjust = 1, kernel = "gaussian")
x, y, | ..count.., ..density.., ..scaled..
f + stat_bin2d(bins = 30, drop = TRUE)
x, y, fill | ..count.., ..density..
f + stat_binhex(bins = 30)
x, y, fill | ..count.., ..density..
f + stat_density2d(contour = TRUE, n = 100)
x, y, color, size | ..level..

2D distributions

m + stat_contour(aes(z = z))
3 Variables
x, y, z, order | ..level..
m+ stat_spoke(aes(radius= z, angle = z))
angle, radius, x, xend, y, yend | ..x.., ..xend.., ..y.., ..yend..
m + stat_summary_hex(aes(z = z), bins = 30, fun = mean)
x, y, z, fill | ..value..
m + stat_summary2d(aes(z = z), bins = 30, fun = mean)
x, y, z, fill | ..value..

title to use in labels to use in


legend/axis
legend/axis

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


theta, start, direction
Polar coordinates

Use with any aesthetic:


alpha, color, fill, linetype, shape, size

r + coord_trans(ytrans = "sqrt")
xtrans, ytrans, limx, limy
Transformed cartesian coordinates. Set
extras and strains to the name
of 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 to
manually chosen visual values

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

Use with x or y aesthetics (x shown here)


scale_x_date(labels = date_format("%m/%d"),
breaks = date_breaks("2 weeks")) - treat x
values as dates. See ?strptime for label formats.
scale_x_datetime() - treat x values as date times. Use
same 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 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

s + geom_bar(position = "fill")

Continuous

g + stat_boxplot(coef = 1.5)
Comparisons
x, y | ..lower.., ..middle.., ..upper.., ..outliers..
g + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area")
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width..

n + scale_fill_brewer(
palette = "Blues")
For palette choices:
library(RcolorBrewer)
display.brewer.all()

f + stat_ecdf(n = 40)
Functions
x, y | ..x.., ..y..
f + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x),
method = "rq")
x, y | ..quantile.., ..x.., ..y..
f + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80,
fullrange = FALSE, level = 0.95)
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax..

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

o + scale_fill_gradient(
low = "red",
high = "yellow")
o + scale_fill_gradient2(
low = "red", hight = "blue",
mid = "white", midpoint = 25)

s + geom_bar(position = "stack")
Stack elements on top of one another

f + geom_point(position = "jitter")
Add random noise to X and Y position
of each element to avoid overplotting
Each position adjustment can be recast as a function
with manual width and height arguments
s + geom_bar(position = position_dodge(width = 1))

Manual Shape values

Manual shape values

p + scale_shape(
solid = FALSE)

13

10

4
5

11

0
+
* |
o %
O #

24

19

25

14

20

15

21

12

16
17

18

22
23

Themes
r + theme_bw()

150

100

50

0
c

fl

150

100

50

Size scales
q <- f + geom_point(
aes(size = cyl))

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

q + scale_size_area(max = 6)
Value mapped to area of circle
(not radius)

t + facet_grid(year ~ .)

facet into rows based on year

t + facet_grid(year ~ fl)

facet into both rows and columns

White background
with grid lines

0
c

fl

Grey background
(default theme)

r + theme_classic()

100

50

0
c

fl

White background
no gridlines

r + theme_minimal()

150

Minimal theme

100

50

0
c

t + facet_wrap(~ fl)

wrap facets into a rectangular layout

Set scales to let axis limits vary across facets

t + facet_grid(y ~ x, 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 labels
t + facet_grid(. ~ fl, labeller = label_both)
fl: d

fl: e

fl: p

fl: r

t + facet_grid(. ~ fl, labeller = label_bquote(alpha ^ .(x)))


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

Labels

t + ggtitle("New Plot Title")

Add a main title above the plot

t + xlab("New X label")
Change the label on the X axis

t + ylab("New Y label")

Use scale functions


to update legend
labels

Change the label on the Y axis

t + labs(title =" New title", x = "New x", y = "New y")


All of the above

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

t + guides(color = "none")
Set legend type for each aesthetic: colorbar, legend,
or none (no legend)

t + scale_fill_discrete(name = "Title",
labels = c("A", "B", "C"))
Set legend title and labels with a scale function.

Zooming

150

r + theme_grey()

count

p + scale_shape_manual(
values = c(3:7))
Shape values shown in
chart on right

Stack elements on top of one another,


normalize height

o + scale_fill_gradientn(
colours = terrain.colors(6))
Also: rainbow(), heat.colors(),
topo.colors(), cm.colors(),
RColorBrewer::brewer.pal()

p <- f + geom_point(
aes(shape = fl))

facet into columns based on fl

fl: c

Position Adjustments

Color and fill scales

Shape scales

60

projection, orientation, xlim, ylim


Map projections from the mapproj package long
(mercator (default), azequalarea, lagrange, etc.)

X and Y location scales

o <- a + geom_dotplot(
aes(fill = ..x..))

ggplot() + stat_function(aes(x = -3:3),


General Purpose
fun = dnorm, n = 101, args = list(sd=0.5))
x | ..y..
f + stat_identity()
ggplot() + stat_qq(aes(sample=1:100), distribution = qt,
dparams = list(df=5))
sample, x, y | ..x.., ..y..
f + stat_sum()
x, y, size | ..size..
f + stat_summary(fun.data = "mean_cl_boot")
f + stat_unique()

xlim, ylim
Flipped Cartesian coordinates

breaks to use in
legend/axis

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

t + facet_grid(. ~ fl)

r + coord_flip()

General Purpose scales

Discrete

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

ratio, xlim, ylim


Cartesian coordinates with fixed aspect
ratio between x and y units

n + 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 to
include in mapping

Facets divide a plot into subplots based on the values


of one or more discrete variables.

r + coord_fixed(ratio = 1/2)

scale specific
arguments

aesthetic prepackaged
to adjust scale to use

lat

count

..count..

xlim, ylim
The default cartesian coordinate system

count

r <- b + geom_bar()
r + coord_cartesian(xlim = c(0, 5))

count

fl cty cyl

Faceting

Coordinate Systems

fl

ggthemes - Package with additional ggplot2 themes

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 0.9.3.1 Updated: 3/15

You might also like