You are on page 1of 2

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

s to represent variables. Each function returns a layer.


Data Visualization Graphical Primitives Two Variables
with ggplot2 a <- ggplot(seals, aes(x = long, y = lat)) Continuous X, Continuous Y Continuous Bivariate Distribution
Cheat Sheet b <- ggplot(economics, aes(date, unemploy)) e <- ggplot(mpg, aes(cty, hwy)) h <- ggplot(diamonds, aes(carat, price))

A C e + geom_label(aes(label = cty), nudge_x = 1, h + geom_bin2d(binwidth = c(0.25, 500))


a + geom_blank() nudge_y = 1, check_overlap = TRUE) x, y, alpha, color, fill, linetype, size, weight
Geoms(Useful
- Use a geom B
Data Visualization for expanding limits)
to represent data points, use the geom’s aesthetic properties to represent variables
x, y, label, alpha, angle, color, family, fontface,
Two Variables hjust, lineheight, size, vjust
with ggplot2 One Variable
a + geom_curve(aes(yend = lat + delta_lat, h + geom_density2d()
Geomsxend
Continuous
- Use=a geom
longto+represent
Continuous X, Continuous Y
delta_long, curvature =hwy))
z)) erepresent
+ggplot(movies,
Continuousgeom_jitter(height
Bivariate Distribution= 2, width = 2)
x, y, alpha, colour, group, linetype, size
Data Visualization
Cheat Sheet
Basics a <- ggplot(mpg, aes(hwy))
One Variable
data points, use the
f <- ggplot(mpg,
x, xend, y, yend, alpha,
f + angle,
geom’s
aes(cty, aesthetic properties to
h <- variables
color, curvature, Two Variablesh +x,geom_bin2d(binwidth
geom_blank()
aes(year, rating))
y, alpha, color, fill,= c(5,shape,
0.5)) size
with ggplot2 a + geom_area(stat
x, y, alpha, Continuous
= "bin")
linetype,
color, fill, linetype, size
size Continuous X, Continuous Y
xmax, xmin, ymax, ymin, alpha, color, fill,
Continuous Bivariate Distribution h + geom_hex()
ggplot2 is based on the
Cheatgrammar
Sheet of graphics, the b + geom_area(aes(y = ..density..), stat = "bin") f <- ggplot(mpg, aes(cty, hwy)) he<-+ggplot(movies,
geom_point()
linetype, size, weight
aes(year, rating)) x, y, alpha, colour, fill, size
idea that you can build every graph from the same
a <- ggplot(mpg,
a + geom_density(kernal b += "gaussian")
aes(hwy))
geom_path(lineend="butt", f + geom_jitter()
f x,
+ geom_blank()
h + geom_density2d()
hx,+x, y, alpha,
y, alpha, colour, color,
linetype, fill,
geom_bin2d(binwidth shape,
= c(5,
size 0.5)) size, stroke
y, alpha, color, fill, shape, size
few components: a data Basics
set, a set of geoms—visual
ax,+y,geom_area(stat linejoin="round’
= "bin")
alpha, color, fill, linetype, size, weight , linemitre=1) xmax, xmin, ymax, ymin, alpha, color, fill,
bx,+y,geom_density(aes(y
alpha, color, fill, linetype, size
= ..county..)) f + geom_point() h +linetype, size, weight
geom_hex() Continuous Function
marks that represent data points, and a coordinate x, y, alpha, color, group,
b + geom_area(aes(y = ..density..), stat = "bin")
a+ geom_dotplot() f x,
linetype, size
+ geom_jitter() ehx,++y,geom_density2d()
geom_quantile()
system. F M A ax,+y,geom_density(kernal
alpha, color, fill
= "gaussian")
y, alpha, color, fill, shape, size
x, y, alpha, color, fill, shape, size
alpha, colour, fill size
x, y, alpha, colour, linetype, size
i <- ggplot(economics, aes(date, unemploy))
4
Basics 4 b + geom_polygon(aes(group
x, y, alpha, color, fill, linetype, size, weight = group))
f + geom_quantile()
x,Continuous
y, alpha, color, group, linetype, size, weight
Function
b + geom_density(aes(y = ..county..)) f x,
+ geom_point() h + geom_hex() aes(date, unemploy))
g <- ggplot(economics, i + geom_area()
x, y, alpha, color, fill, group, linetype, sizesize
3 3
a + geom_freqpoly() y, alpha, color, linetype, size, weight
+ 2
= 2 a+ geom_dotplot()
x, y, alpha, color, linetype, size
x, y, alpha, color, fill, shape, ge+x,+ geom_rug(sides
y, alpha, colour, fill size
geom_area() = "bl") x, y, alpha, color, fill, linetype, size
1 1
x, y, alpha, color, fill f + geom_rug(sides = "bl")
F MA 0
4
0 1 3 4
0
4
0 1 3 4
a + geom_rect(aes(xmin
b + geom_freqpoly(aes(y = ..density..))
a + geom_histogram(binwidth = 5)
=color,
f alpha, long,
+ geom_quantile() ymin
linetype, size = lat,
x, y, alpha, color, fill, linetype, size
x, Continuous
y, alpha, color, linetype, size
Function
g <- ggplot(economics, aes(date, unemploy))
2

)
2
data geom coordinate xmax= long + delta_long, x, y,ymax = latlinetype,
+ delta_lat) i + geom_line()
3
plot
3
ax,+y,geom_freqpoly() alpha, color, size, weight g + geom_line()
x=F + system = alpha, color, fill, linetype, size, weight
f + geom_smooth(model = lm)
2 2
x, y, alpha, color, linetype, xmax,
size xmin, ymax, ymin, alpha, color, fill, linetype, size gx,+y,geom_area()
alpha, color, linetype, size
e x,+y,geom_smooth(method = lm)
y=A
1 1 b + geom_histogram(aes(y = ..density..))
b + geom_freqpoly(aes(y = ..density..)) f x,
+ geom_rug(sides = "bl") size, weight
y, alpha, color, fill, linetype, alpha, color, fill, linetype, size x, y, alpha, color, group, linetype, size
To display data values, map 2 variables in the data set alpha, color, linetype, size
0 0
Discrete g + x, geom_step(direction = "hv")
y, alpha, color, fill, group, linetype, size, weight
a + geom_histogram(binwidth baes(fl))
+ geom_ribbon(
= 5) aes(ymin=unemploy - 900,
0 1 3 4 0 1 2 3 4

data geom coordinate plot f + geom_text(aes(label = cty)) gx,+y,geom_line()


to aesthetic properties
A x = F 4 ofsystem the geom like size, color, x, y,aalpha,
<- ggplot(mpg, alpha, color, linetype, size
F M
y=A
4

b +bgeom_bar()
color, fill, linetype,
+ geom_histogram(aes(y = ..density..))
size, weight
ymax=unemploy + 900) + )geom_smooth(model
f x, y, label, alpha, angle, color, = lm)
family, fontface, x, y, alpha, color, linetype, size i + geom_step(direction = "hv")
and x and y locations.2 hjust, lineheight,
color,size, vjust size, weight
e + geom_text(aes(label = cty), nudge_x = 1,
3 3
x, y, alpha, fill, linetype,
+ = 2 x, alpha, color, fill,
Discretelinetype, x, ymax,
size, weightymin, alpha, color, fill, group, linetype, size C Visualizing error
g + geom_step(direction
df <- data.frame(grp = c("A", "B"), fit = "hv")
= 4:5, se = 1:2)
x, y, alpha, color, group, linetype, size
F MA
1

04
1

04
a <- ggplot(mpg, aes(fl))
a + geom_segment(aes(yend=lat
f + geom_text(aes(label = cty))
Discrete + delta_lat,
X, Continuous
x, y, label, alpha, angle,
AB Y
color, family, fontface,
e <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se)) = TRUE)
nudge_y
x, y, alpha, color, = 1, check_overlap
linetype, size
0 1 3 4 0 1 3 4
b + geom_bar()
Graphical Primitives x, y, label, alpha, angle, color, family, fontface,
xend = long + delta_long))
2 2
data geom coordinate 3 3
plot g <- ggplot(mpg,
hjust, lineheight,aes(class,
size, vjust hwy))
x=F 2
+ system = 2 x, alpha, color, fill, linetype, size, weight e + geom_crossbar(fatten
hjust, lineheight,
Visualizing error=size,2)
vjust Visualizing error
y=A
color = F 1 1
c <- ggplot(map, aes(long,
x, xend,
lat))
y, yend, alpha, g +color,
geom_bar(stat linetype, size
= "identity") df <- data.frame(grp
x, y, ymax, ymin,
size
= c("A",
alpha,"B"), fit =fill,4:5,
color, se = 1:2)
linetype,
df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
size = A
x,Discrete
y, alpha, color, X, fill, linetype, size,
Continuous Y weight e <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))
j <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))
0 0

e + geom_errorbar()
c + geom_polygon(aes(group
a + geom_spoke(aes(yend
= group))
= lat + delta_lat,
0 1 3 4 0 1 3 4
Graphical Primitives
2 2
data geom coordinate g <- ggplot(mpg, aes(class, hwy)) Discreteymin, alpha,X, color,Continuous Y
plot ex,+ymax,
geom_crossbar(fatten = 2)
system x, y, alpha, color, fill, linetype, size g + geom_boxplot() linetype, size,
xend = long + delta_long))
x=F
y=A glower,
+ geom_bar(stat
middle, upper,=x,"identity")
ymax, ymin, alpha, fwidth
x,<- ggplot(mpg,
y, ymax, geom_errorbarh())
(also ymin, alpha, color, aes(class,
fill, linetype, hwy))
color = F
size = A c <- ggplot(map, aes(long, lat))
x, y, angle, radius, alpha, x, y,color,
color, linetype,
fill, linetype,
alpha, color, shape,
fill, size
size,
linetype, weight
size, weight e +size geom_linerange() j + geom_crossbar(fatten = 2)
c + geom_polygon(aes(group = group)) g + geom_dotplot(binaxis = "y", ex,+ymin,
geom_errorbar()
Build a graph with ggplot() or qplot() g <- ggplot(economics, aes(date, unemploy)) gstackdir
+ geom_boxplot() f +x, ymax,
ymax, alpha, color, linetype, size
geom_bar(stat
ymin, alpha, color, linetype, = "identity")
size,
x, y, ymax, ymin, alpha, color, fill, group,
x, y, alpha, color, fill, linetype, size = "center")
g + geom_path(lineend="butt", x,lower,
y, alpha, color,upper,
middle, fill x, ymax, ymin, alpha, e +width (also geom_errorbarh())
geom_pointrange() linetype, size
ex,+x, y, alpha, color,color,fill, linetype, size, weight
ggplot(data = mpg, aes(x = cty, y = hwy)) linejoin="round’, linemitre=1)
x, y, alpha, color, linetype, size
One Variable g +color, fill, linetype, shape,
geom_violin(scale
gx,+y,geom_dotplot(binaxis
alpha, color, fill,
size, weight
= "area")
linetype, =size,
"y", weight
y,geom_linerange()
shape,
ymin,
x, ymin,size
ymax, alpha, fill, linetype,
ymax, alpha, color, linetype, size
j + geom_errorbar()
Begins a plotF M that A you finish by adding
g <- ggplot(economics, aes(date, unemploy))
layers to. No gg+ymax=unemploy geom_ribbon(aes(ymin=unemploy - 900, stackdir = "center") f +geom_pointrange()
geom_boxplot() x, ymax, ymin, alpha, color, group, linetype,
4 4

+ 900))
+ geom_path(lineend="butt", Continuous x, y, alpha, color, fill data e<-+data.frame(murder
Maps
= USArrests$Murder, size, width (also geom_errorbarh())
defaults, but provides more control2 than qplot().
3 3

statex,=x,y,tolower(rownames(USArrests)))
y, lower, middle, upper,
linetype,ymax, ymin, alpha,
2
+ = x,linejoin="round’
ymax, ymin, alpha, , linemitre=1)
c <- ggplot(mpg,
color, fill, linetype, size gaes(hwy))
+ geom_violin(scale
Discrete X, Discrete = "area")
Y
map <-
ymin, ymax, alpha,
map_data("state")
shape, size
color, fill,
j + geom_linerange()
dataF M A 1 1 x, y, alpha, color, linetype, size h <-x,ggplot(diamonds,
y, alpha, color, fill, linetype,
aes(cut, size, weight
color)) color,
e <- ggplot(data, fill,
aes(fillgroup,
= murder)) linetype, shape, size, weight
04 04 add layers, d<-g + geom_ribbon(aes(ymin=unemploy - 900,
c + geom_area(stat = "bin") e + geom_map(aes(map_id Maps = state), map = map) + x, ymin, ymax, alpha, color, group, linetype, size
ggplot(seals,
ymax=unemploy aes(x
+ =
900) long,
) y = lat)) h + geom_jitter() dataf<-+data.frame(murder
geom_dotplot(binaxis = USArrests$Murder, = "y",
1
elements with + x, ymax, ymin, alpha, color, fill, linetype, size
0 1 2 3 4 0 2 3 4

data geom 3 coordinate 3


plot expand_limits( x = map$long, y = map$lat)
ggplot(mpg, aes(hwy, cty))
system + 2 d + geom_segment(aes( x, y, alpha, color, fill, linetype, size
x, y,Discrete
alpha, color, X,fill, shape, size state = tolower(rownames(USArrests)))
geom_point(aes(color
x=F
y=A
2
+ = cyl)) 1 +
= layer = geom + xend = long + delta_long,
Discrete
h <- ggplot(diamonds, aes(cut, color))
Y
<-stackdir
mapmap_id, = "center")
alpha, color, fill, linetype, size
map_data("state")
j + geom_pointrange()
= lat + delta_lat)) a + geom_area(aes(y = ..density..), stat = "bin")
1
e <- ggplot(data, aes(fill = murder))
geom_smooth(method 0 ="lm") + 0 0 1 2 default stat + d<-yendggplot(seals, aes(x = long, y = lat)) h + geom_jitter() Three Variables e + x, y,
geom_map(alpha, color,= state),
aes(map_id fill, map group = map) + x, y, ymin, ymax, alpha, color, fill, group,
plotlayer specific x, xend, y, yend, alpha, color, linetype, size
0 1 2 3 4 3 4

coord_cartesian()data geom + coordinate expand_limits( x = map$long, y = map$lat) linetype, shape, size


scale_color_gradient()
x=F
y=A
system
+ mappings dd++geom_rect(aes(xmin
geom_segment(aes( c =+long,
geom_density(kernel
ymin = lat,
seals$z <- with(seals,
= "gaussian")
x, y, alpha, color, fill, shape, size+ delta_lat^2))
sqrt(delta_long^2 fi ++ geom_violin(scale
geom_raster(aes(fill = z),
map_id, alpha, color, fill, linetype, size
hjust=0.5, = "area")
xend =long long++delta_long,
delta_long, i <- ggplot(seals, aes(long, lat)) vjust=0.5, interpolate=FALSE)
theme_bw() additional ymax
xmax=
yend == lat delta_lat)) x, y, alpha, color, fill, group, linetype, size, weight
lat ++ delta_lat)) x, y, alpha, color, fill, group, linetype, size,
Three Variables x, y, alpha, fill
elements x, xend, y, yend, alpha, color,
xmax, xmin, ymax, ymin, alpha, color, fill,linetype, size i + geom_contour(aes(z = z)) i + weight
geom_tile(aes(fill = z))
Maps
seals$z <-x,with(seals,
y, z, alpha, sqrt(delta_long^2
colour, linetype, size, + delta_lat^2))
weight i +x, geom_raster(aes(fill = z),size
hjust=0.5,
Add a new layer to a plot with a geom_*() dlinetype, size
+ geom_rect(aes(xmin c + geom_dotplot()
= long, ymin = lat, i <- ggplot(seals, aes(long, lat))
y, alpha, color, fill, linetype,
vjust=0.5, interpolate=FALSE) data <- data.frame(murder = USArrests$Murder,
xmax= long + delta_long,
or stat_*()
RStudio® is a function.
trademark of RStudio, Each Inc. • provides a geom, a• 844-448-1212ymax
CC BY RStudio • info@rstudio.com = lat + delta_lat)) x, y, alpha, color, fill
• rstudio.com
x, y, alpha, fill
Discrete
Learn more at docs.ggplot2.org X, 0.9.3.1
• ggplot2 Discrete • Updated: 3/15Y
state = tolower(rownames(USArrests)))
i + geom_contour(aes(z = z)) i + geom_tile(aes(fill = z)) map <- map_data("state")
set of aesthetic mappings, and a default stat xmax, xmin, ymax, ymin, alpha, color, fill,
x, y, z, alpha, colour, linetype, size, weight g <-x, ggplot(diamonds,
y, alpha, color, fill, linetype, size aes(cut, color)) k <- ggplot(data, aes(fill = murder))
linetype, size
c + geom_freqpoly()
and position adjustment. k + geom_map(aes(map_id = state), map = map) +
RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com x, y, alpha, color, group, linetype, size g + geom_count()
Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15

aesthetic mappings data geom a + geom_freqpoly(aes(y = ..density..)) x, y, alpha, color, fill, shape, size, stroke expand_limits(x = map$long, y = map$lat)
map_id, alpha, color, fill, linetype, size
qplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point")
c + geom_histogram(binwidth = 5)
Creates a complete plot with given data, geom, and
mappings. Supplies many useful defaults. x, y, alpha, color, fill, linetype, size, weight Three Variables
a + geom_histogram(aes(y = ..density..)) seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2)) l + geom_raster(aes(fill = z), hjust=0.5,
last_plot()
Discrete l <- ggplot(seals, aes(long, lat)) vjust=0.5, interpolate=FALSE)
Returns the last plot
d <- ggplot(mpg, aes(fl)) x, y, alpha, fill
ggsave("plot.png", width = 5, height = 5) l + geom_contour(aes(z = z))
d + geom_bar() l + geom_tile(aes(fill = z))
Saves last plot as 5’ x 5’ file named "plot.png" in x, y, z, alpha, colour, group, linetype, size, x, y, alpha, color, fill, linetype, size, width
working directory. Matches file type to file extension. x, alpha, color, fill, linetype, size, weight weight

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 2.0.0 • Updated: 12/15
Stats - An alternative way to build a layer Scales Coordinate Systems Faceting
Some plots visualize a transformation of the original data set. Scales control how a plot maps data values to the visual r <- d + geom_bar() Facets divide a plot into subplots based on the values
Use a stat to choose a common transformation to visualize, values of an aesthetic. To change the mapping, add a of one or more discrete variables.
e.g. a + geom_bar(stat = "count") r + coord_cartesian(xlim = c(0, 5)) t <- ggplot(mpg, aes(cty, hwy)) + geom_point()
custom scale.
fl cty cyl n <- b + geom_bar(aes(fill = fl)) xlim, ylim
t + facet_grid(. ~ fl)
4 4
x ..count..
3 3
n The default cartesian coordinate system
+ 2
= 2
facet into columns based on fl
aesthetic prepackaged scale specific r + coord_fixed(ratio = 1/2)
t + facet_grid(year ~ .)
1 1

scale_
0
0 1
0
0 1 3 4 to adjust scale to use arguments ratio, xlim, ylim
facet into rows based on year
2 3 4 2

data stat geom coordinate plot


x=x system n + scale_fill_manual( Cartesian coordinates with fixed aspect
t + facet_grid(year ~ fl)
y = ..count..

Each stat creates additional variables to map aesthetics values = c("skyblue", "royalblue", "blue", "navy"), ratio between x and y units
limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", "r"),
facet into both rows and columns
to. These variables use a common ..name.. syntax. r + coord_flip()
name = "fuel", labels = c("D", "E", "P", "R")) t + facet_wrap(~ fl)
stat and geom functions both combine a stat with a xlim, ylim wrap facets into a rectangular layout
geom to make a layer, i.e. stat_count(geom="bar") range of values to title to use in labels to use in breaks to use in Flipped Cartesian coordinates
does the same as geom_bar(stat="count") include in mapping legend/axis legend/axis legend/axis
r + coord_polar(theta = "x", direction=1 ) Set scales to let axis limits vary across facets
stat function layer mappings theta, start, direction t + facet_grid(drv ~ fl, scales = "free")
General Purpose scales
i + stat_density2d(aes(fill = ..level..), Polar coordinates x and y axis limits adjust to individual facets
Use with any aesthetic:
geom = "polygon", n = 100) variable alpha, color, fill, linetype, shape, size r + coord_trans(ytrans = "sqrt") • "free_x" - x axis limits adjust
created by xtrans, ytrans, limx, limy • "free_y" - y axis limits adjust
geom for layer parameters for stat transformation scale_*_continuous() - map cont’ values to visual values
Transformed cartesian coordinates. Set
scale_*_discrete() - map discrete values to visual values Set labeller to adjust facet labels
c + stat_bin(binwidth = 1, origin = 10) 1D distributions xtrans and ytrans to the name
x, y | ..count.., ..ncount.., ..density.., ..ndensity.. scale_*_identity() - use data values as visual values of a window function. t + facet_grid(. ~ fl, labeller = label_both)
c + stat_count(width = 1) scale_*_manual(values = c()) - map discrete values to
60

π + coord_map(projection = "ortho", fl: c fl: d fl: e fl: p fl: r


x, y, | ..count.., ..prop.. manually chosen visual values
orientation=c(41, -74, 0))

lat
c + stat_density(adjust = 1, kernel = "gaussian") t + facet_grid(fl ~ ., labeller = label_bquote(alpha ^ .(fl)))
x, y, | ..count.., ..density.., ..scaled.. X and Y location scales projection, orientation, xlim, ylim ↵c ↵d ↵e ↵p ↵r
e + stat_bin_2d(bins = 30, drop = TRUE)
Use with x or y aesthetics (x shown here) Map projections from the mapproj package long t + facet_grid(. ~ fl, labeller = label_parsed)
2D distributions (mercator (default), azequalarea, lagrange, etc.)
x, y, fill | ..count.., ..density.. scale_x_date(date_labels = "%m/%d"), c d e p r
e + stat_bin_hex(bins = 30) date_breaks = "2 weeks") - treat x values as dates.
x, y, fill | ..count.., ..density.. See ?strptime for label formats.
e + stat_density_2d(contour = TRUE, n = 100) scale_x_datetime() - treat x values as date times. Use Position Adjustments Labels
x, y, color, size | ..level.. same arguments as scale_x_date(). Position adjustments determine how to arrange t + ggtitle("New Plot Title")
e + stat_ellipse(level = 0.95, segments = 51, type = "t") geoms that would otherwise occupy the same space. Add a main title above the plot
scale_x_log10() - Plot x on log10 scale
l + stat_contour(aes(z = z)) 3 Variables scale_x_reverse() - Reverse direction of x axis s <- ggplot(mpg, aes(fl, fill = drv)) t + xlab("New X label") Use scale functions
x, y, z, order | ..level.. to update legend
scale_x_sqrt() - Plot x on square root scale s + geom_bar(position = "dodge") Change the label on the X axis
l + stat_summary_hex(aes(z = z), bins = 30, fun = mean) labels
x, y, z, fill | ..value.. Arrange elements side by side t + ylab("New Y label")
l + stat_summary_2d(aes(z = z), bins = 30, fun = mean) Color and fill scales s + geom_bar(position = "fill") Change the label on the Y axis
x, y, z, fill | ..value.. Discrete Continuous Stack elements on top of one another, t + labs(title =" New title", x = "New x", y = "New y")
f + stat_boxplot(coef = 1.5) normalize height All of the above
Comparisons n <- d + geom_bar( o <- c + geom_dotplot(
x, y | ..lower.., ..middle.., ..upper.., ..width.. , ..ymin.., ..ymax.. aes(fill = fl)) aes(fill = ..x..)) e + geom_point(position = "jitter")
f + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area")
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width..
n + scale_fill_brewer(
palette = "Blues")
o + scale_fill_gradient(
low = "red",
Add random noise to X and Y position of each
element to avoid overplotting
Legends
high = "yellow") n + theme(legend.position = "bottom")
A
For palette choices: e + geom_label(position = "nudge")
e + stat_ecdf(n = 40) Functions library(RColorBrewer) o + scale_fill_gradient2( B
x, y | ..x.., ..y.. display.brewer.all() low = "red", high = "blue", Nudge labels away from points Place legend at "bottom", "top", "left", or "right"
mid = "white", midpoint = 25)
e + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x), n + scale_fill_grey( s + geom_bar(position = "stack") n + guides(fill = "none")
o + scale_fill_gradientn(
method = "rq") start = 0.2, end = 0.8, colours = terrain.colors(6)) Stack elements on top of one another Set legend type for each aesthetic: colorbar, legend,
x, y | ..quantile.. na.value = "red") Also: rainbow(), heat.colors(), or none (no legend)
e + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80, topo.colors(), cm.colors(), Each position adjustment can be recast as a function
fullrange = FALSE, level = 0.95) RColorBrewer::brewer.pal() with manual width and height arguments n + scale_fill_discrete(name = "Title",
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. labels = c("A", "B", "C", "D", "E"))
Shape scales s + geom_bar(position = position_dodge(width = 1))
Manual Shape values
Manual shape values Set legend title and labels with a scale function.
ggplot() + stat_function(aes(x = -3:3), General Purpose p <- e + geom_point(aes(
fun = dnorm, n = 101, args = list(sd=0.5)) shape = fl, size = cyl))
0 6 12 18 24 0 0

x | ..x.., ..y.. 1 7 13 19 25 + + Themes Zooming


e + stat_identity(na.rm = TRUE) p + scale_shape(
ggplot() + stat_qq(aes(sample=1:100), distribution = qt,
solid = FALSE) 2 8 14 20 *
* - - 150

r + theme_bw()
150

r + theme_classic()
Without clipping (preferred)
| t + coord_cartesian(
100
count

100
count

3 9 15 21 . |
dparams = list(df=5)) p + scale_shape_manual( r + theme_light()
50 50

White background
o % xlim = c(0, 100), ylim = c(10, 20))
0 0

values = c(3:7))
c d e p r c d e p r

sample, x, y | ..sample.., ..theoretical.. 4 10 16 22 o %


with grid lines
fl fl

Shape values shown in


r + theme_linedraw()
e + stat_sum() O #
150

r + theme_gray()
150

chart on right
5 11 17 23 O # 100

r + theme_minimal()
count

With clipping (removes unseen data points)


100
count

x, y, size | ..n.., ..prop..


50

Grey background
50

Minimal themes
0

e + stat_summary(fun.data = "mean_cl_boot") t + xlim(0, 100) + ylim(10, 20)


c d e p r 0

fl

(default theme)
c d e p r
fl

Size scales r + theme_void()


h + stat_summary_bin(fun.y = "mean", geom = "bar")
150

p + scale_radius( p + scale_size_area(
100

r + theme_dark() t + scale_x_continuous(limits = c(0, 100)) +


count

e + stat_unique() range=c(1,6)) Empty theme scale_y_continuous(limits = c(0, 100))


max_scale = 6)
50

dark for contrast


p + scale_size() Maps to area of circle (not radius)
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 • ggplot2 2.0.0 • Updated: 12/15

You might also like