Professional Documents
Culture Documents
Ggplot2 Cheatsheet PDF
Ggplot2 Cheatsheet PDF
b +bgeom_bar()
color, fill, linetype,
+ geom_histogram(aes(y = ..density..))
Discrete f x,
+ geom_smooth(model
y, label, alpha, angle, color, = lm)
family, fontface, x, y, alpha, color, linetype, size j + geom_step(direction = "hv")
and x and y locations.2 hjust, lineheight,
color,size, vjust size, weight
f + geom_text(aes(label = cty))
3 3
x, y, alpha, fill, linetype,
+ = 2 x, alpha, color, fill,
Discretelinetype, size, b <- ggplot(mpg, aes(fl))
weight 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, linetype, size
1 1
a <- ggplot(mpg, aes(fl)) f + geom_text(aes(label = cty)) AB e <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se)) family, fontface,
x,
x, y, y, label,
alpha, color, alpha,
linetype, angle,
size color,
F MA 04
0 1 3 4
04
0 1 3 4
b + geom_bar()
b + geom_bar() Discrete
x, y, label, alpha,X, Continuous
angle, color, family,Y fontface, hjust, lineheight, size, vjust
Graphical Primitives
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, x, alpha,
size, weightcolor, fill, linetype, size, weight e + geom_crossbar(fatten
Visualizing error= 2) Visualizing error
y=A
color = F 1
size = A
1
c <- ggplot(map, aes(long, lat))
g + geom_bar(stat = "identity") df <- data.frame(grp
e <- ggplot(df,
x, y, ymax, ymin, = c("A",
alpha, "B"), fit =fill,4:5,
color,
size aes(grp, fit, ymin = fit-se, ymax = fit+se))
se = 1:2)
linetype,
df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
x,Discrete
y, alpha, color, X, fill, linetype, size,
Continuous Y weight
k <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))
0 0
0 1 2 3 4 0 1 2 3 4
c + geom_polygon(aes(group
Graphical Primitives= group)) g <- ggplot(mpg, aes(class, hwy)) e + geom_errorbar()
data geom coordinate
system
plot
x, y, alpha, color, fill, linetype, size g + geom_boxplot() Discrete
ex,+ymax, ymin, alpha,X,
geom_crossbar(fatten Continuous
color, = 2)
linetype, size, Y
Graphical Primitives
x=F
y=A glower,
+ geom_bar(stat
middle, upper,=x,"identity")
ymax, ymin, alpha, gwidth
x, <- ggplot(mpg,
(also
y, ymax, ymin, alpha, color,aes(class,
geom_errorbarh()) fill, linetype, hwy))
color = F
size = A c <- ggplot(map, aes(long, lat)) color, fill, linetype,
x, y, alpha, shape,
color, fill, size, size,
linetype, weightweight e +sizegeom_linerange() k + geom_crossbar(fatten = 2)
c + geom_polygon(aes(group = group)) g + geom_dotplot(binaxis = "y", ex,+ymin,
geom_errorbar()
ymax, alpha, color, linetype, size
Build a graph with ggplot() or qplot() g <- ggplot(economics, aes(date, unemploy))
x, y, alpha, color, fill, linetype, size
map <- map_data("state")
gstackdir
+ geom_boxplot()
= "center") g x,+ymax, geom_bar(stat
ymin, alpha, color, linetype, = "identity")
size, x, y, ymax, ymin, alpha, color, fill, linetype,
g + geom_path(lineend="butt", c <- ggplot(map, aes(long, x,lower,
y, alpha, lat))
color,
middle, fill x, ymax, ymin, alpha,
upper, e +width (also geom_errorbarh())
geom_pointrange() size
linejoin="round’, linemitre=1) g +color, fill, linetype, shape,
geom_violin(scale size, weight
= "area") ex,+x, y, alpha,
y,geom_linerange()
ymin, ymax, alpha,color,color,fill, linetype, size, weight
fill, linetype,
ggplot(data = mpg, aes(x = cty, y = hwy)) x, y, alpha, color, linetype, c + geom_polygon(aes(group
size gx,+y,geom_dotplot(binaxis
alpha, color,= group))
fill, linetype, =size,
"y", weight shape,
x, ymin,size
ymax, alpha, color, linetype, size k + geom_errorbar()
g <- ggplot(economics, aes(date, unemploy))
Begins a plot
F M thatA you finish by adding layers to. No g + geom_ribbon(aes(ymin=unemploy - 900, stackdir = "center") g +geom_pointrange()
geom_boxplot() x, ymax, ymin, alpha, color, linetype, size,
+ 900)) x, y, alpha, color, fill, linetype, sizefill
4 4
Maps
gymax=unemploy
+ geom_path(lineend="butt", x, y, alpha, color, data e<-+data.frame(murder = USArrests$Murder,
defaults, but provides more
3
control2 than qplot().
3
x,linejoin="round’
ymax, ymin, alpha, , linemitre=1)
color, fill, linetype, size g + geom_violin(scale = "area") statex,=lower, middle, upper,
y,tolower(rownames(USArrests)))
ymin, ymax, alpha, color, x, ymax, ymin, alpha,
fill, linetype, width (also geom_errorbarh())
2
+ = Discrete X, Discrete Y
map <- map_data("state")
shape, size
data 1 1 x, y, alpha, color, linetype, size
g + geom_ribbon(aes(ymin=unemploy - 900,
h <-x,ggplot(diamonds,
y, alpha, color, fill, linetype,
aes(cut, size, weight
color)) color,
e <- ggplot(data, fill, linetype,
aes(fill = murder)) shape, size, weight k + geom_linerange()
F MA 04 04 add layers, d<- e + geom_map(aes(map_id Maps = state), map = map) +
elements with + ymax=unemploy
ggplot(seals, aes(x + 900)= long,
) y = lat)) h + geom_jitter() datag<-+ geom_dotplot(binaxis = USArrests$Murder, = "y", x, ymin, ymax, alpha, color, linetype, size
0 1 3 4 0 1 2 3 4
ggplot(seals, aes(x d
geom_smooth(method 0 ="lm") + 0 0 1 2 default stat + d<-yend = lat + delta_lat)) + geom_path(lineend="butt", Three Variables e + x, y,
geom_map(alpha, color,= state),
aes(map_id fill map = map) +
= long, y = lat)) h + geom_jitter()
plotlayer specific x, xend, y, yend, alpha, color,
0 1 2 3 4 3 4
coord_cartesian()
data geom + coordinate
x=F system mappings dd++geom_rect(aes(xmin linejoin="round’
geom_segment(aes(= long, ymin = lat,
linetype, size
, linemitre=1)
seals$z x, y, alpha, color,
<- with(seals, fill, shape, size+ delta_lat^2))
sqrt(delta_long^2 gi map_id,
++ geom_violin(scale
expand_limits(
geom_raster(aes(fillx = map$long, = map$lat)
= z),yhjust=0.5, = "area") x, y, ymin, ymax, alpha, color, fill, linetype,
scale_color_gradient() y=A + vjust=0.5,
alpha, color, fill, linetype, size
interpolate=FALSE) shape, size
theme_bw()
xend =long
xmax= long++delta_long,
delta_long, x, y, alpha, color,
i
linetype,
<- ggplot(seals,
size
aes(long, lat))
x, y, alpha, color, fill, linetype, size, weight
additional ymax yend == lat lat ++ delta_lat))
delta_lat)) Three Variables x, y, alpha, fill
elements x, xend, y, yend, alpha, d +
color, geom_ribbon(
xmax, xmin, ymax, ymin, alpha, color, fill,linetype, size aes(ymin=unemploy
i + geom_contour(aes(z = z)) - 900, i + geom_tile(aes(fill = z))
i +x, geom_raster(aes(fill = z),size
hjust=0.5, Maps
seals$z <-x,with(seals,
y, z, alpha, sqrt(delta_long^2 + delta_lat^2))
Add a new layer to a plot with a geom_*() dlinetype, size
+ geom_rect(aes(xmin ymax=unemploy
= long, ymin = lat, + 900) )
i <- ggplot(seals, aes(long, lat))
colour, linetype, size, weight y, alpha, color, fill, linetype,
vjust=0.5, interpolate=FALSE) data <- data.frame(murder = USArrests$Murder,
xmax= long + delta_long, x, ymax, ymin, alpha, color, fill, linetype, size x, y, alpha, fill state = tolower(rownames(USArrests)))
or stat_*()
RStudio® is afunction.
trademark of RStudio, Each Inc. • provides a geom, a• 844-448-1212ymax
CC BY RStudio • info@rstudio.com = lat + delta_lat))
• rstudio.com Discrete
Learn more at docs.ggplot2.org X, 0.9.3.1
• ggplot2 Discrete • Updated: 3/15Y
xmax, xmin, ymax, ymin, alpha, color, fill,
i + geom_contour(aes(z = z)) i + geom_tile(aes(fill = z)) map <- map_data("state")
set of aesthetic mappings, and a default stat linetype, size x, y, z, alpha, colour, linetype, size, weight h <-x, ggplot(diamonds,
y, alpha, color, fill, linetype, size aes(cut, color)) l <- ggplot(data, aes(fill = murder))
and position adjustment. l + 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 e <- ggplot(seals, aes(x = long, y = lat)) h + geom_jitter()
Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15
aesthetic mappings data geom x, y, alpha, color, fill, shape, size expand_limits(x = map$long, y = map$lat)
e + geom_segment(aes( map_id, alpha, color, fill, linetype, size
qplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point") xend = long + delta_long,
Creates a complete plot with given data, geom, and yend = lat + delta_lat))
mappings. Supplies many useful defaults. Three Variables
x, xend, y, yend, alpha, color, linetype, size
seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2)) m + geom_raster(aes(fill = z), hjust=0.5,
last_plot() e + geom_rect(aes(xmin = long, ymin = lat, m <- ggplot(seals, aes(long, lat)) vjust=0.5, interpolate=FALSE)
Returns the last plot xmax= long + delta_long,
ymax = lat + delta_lat)) x, y, alpha, fill (fast)
ggsave("plot.png", width = 5, height = 5) m + geom_contour(aes(z = z)) m + geom_tile(aes(fill = z))
Saves last plot as 5’ x 5’ file named "plot.png" in xmax, xmin, ymax, ymin, alpha, color, fill,
linetype, size x, y, z, alpha, colour, linetype, size, weight x, y, alpha, color, fill, linetype, size (slow)
working directory. Matches file type to file extension.
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 1.0.0 • Updated: 4/15
Stats - An alternative way to build a layer Scales Coordinate Systems Faceting
Scales control how a plot maps data values to the visual Facets divide a plot into subplots based on the values
Some plots visualize a transformation of the original data set. r <- b + geom_bar()
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 = "bin")
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
1 1
aesthetic prepackaged scale specific r + coord_fixed(ratio = 1/2)
0 0
0 1
scale_
to adjust scale to use arguments ratio, xlim, ylim
t + facet_grid(year ~ .)
facet into rows based on year
0 1 2 3 4 2 3 4
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 functions and geom functions both combine a stat xlim, ylim wrap facets into a rectangular layout
with a geom to make a layer, i.e. stat_bin(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="bin") 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
layer specific variable created theta, start, direction t + facet_grid(y ~ x, scales = "free")
stat function mappings by transformation General Purpose scales
Polar coordinates x and y axis limits adjust to individual facets
Use with any aesthetic:
i + stat_density2d(aes(fill = ..level..), alpha, color, fill, linetype, shape, size r + coord_trans(ytrans = "sqrt") • "free_x" - x axis limits adjust
geom = "polygon", n = 100) xtrans, ytrans, limx, limy • "free_y" - y axis limits adjust
scale_*_continuous() - map cont’ values to visual values
geom for layer parameters for stat scale_*_discrete() - map discrete values to visual values Transformed cartesian coordinates. Set
xtrans and ytrans to the name Set labeller to adjust facet labels
a + stat_bin(binwidth = 1, origin = 10) scale_*_identity() - use data values as visual values of a window function.
1D distributions t + facet_grid(. ~ fl, labeller = label_both)
x, y | ..count.., ..ncount.., ..density.., ..ndensity.. scale_*_manual(values = c()) - map discrete values to
60
a + stat_bindot(binwidth = 1, binaxis = "x") manually chosen visual values z + coord_map(projection = "ortho", fl: c fl: d fl: e fl: p fl: r
orientation=c(41, -74, 0))
lat
x, y, | ..count.., ..ncount.. t + facet_grid(. ~ fl, labeller = label_bquote(alpha ^ .(x)))
a + stat_density(adjust = 1, kernel = "gaussian") X and Y location scales projection, orientation, xlim, ylim ↵c ↵d ↵e ↵p ↵r
x, y, | ..count.., ..density.., ..scaled.. Use with x or y aesthetics (x shown here) Map projections from the mapproj package long t + facet_grid(. ~ fl, labeller = label_parsed)
f + stat_bin2d(bins = 30, drop = TRUE) scale_x_date(labels = date_format("%m/%d"), (mercator (default), azequalarea, lagrange, etc.) c d e p r
2D distributions
x, y, fill | ..count.., ..density.. breaks = date_breaks("2 weeks")) - treat x
f + stat_binhex(bins = 30) values as dates. See ?strptime for label formats.
x, y, fill | ..count.., ..density.. Position Adjustments Labels
scale_x_datetime() - treat x values as date times. Use
f + stat_density2d(contour = TRUE, n = 100)
same arguments as scale_x_date(). Position adjustments determine how to arrange t + ggtitle("New Plot Title")
x, y, color, size | ..level..
scale_x_log10() - Plot x on log10 scale geoms that would otherwise occupy the same space. Add a main title above the plot
m + 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
s + geom_bar(position = "dodge") Change the label on the X axis
m+ stat_spoke(aes(radius= z, angle = z)) scale_x_sqrt() - Plot x on square root scale labels
angle, radius, x, xend, y, yend | ..x.., ..xend.., ..y.., ..yend.. Arrange elements side by side t + ylab("New Y label")
m + stat_summary_hex(aes(z = z), bins = 30, fun = mean) Color and fill scales Change the label on the Y axis
x, y, z, fill | ..value.. Discrete Continuous s + geom_bar(position = "fill") t + labs(title =" New title", x = "New x", y = "New y")
m + stat_summary2d(aes(z = z), bins = 30, fun = mean) Stack elements on top of one another,
x, y, z, fill | ..value.. n <- b + geom_bar( o <- a + geom_dotplot( All of the above
aes(fill = fl)) aes(fill = ..x..))
normalize height
g + stat_boxplot(coef = 1.5) Comparisons n + scale_fill_brewer( o + scale_fill_gradient( s + geom_bar(position = "stack") Legends
x, y | ..lower.., ..middle.., ..upper.., ..outliers.. palette = "Blues") low = "red",
For palette choices: high = "yellow") Stack elements on top of one another t + theme(legend.position = "bottom")
g + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area") o + scale_fill_gradient2(
library(RcolorBrewer) Place legend at "bottom", "top", "left", or "right"
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width.. display.brewer.all() low = "red", high = "blue", f + geom_point(position = "jitter")
mid = "white", midpoint = 25)
f + stat_ecdf(n = 40) n + scale_fill_grey( o + scale_fill_gradientn( Add random noise to X and Y position t + guides(color = "none")
Functions
x, y | ..x.., ..y.. start = 0.2, end = 0.8, colours = terrain.colors(6)) of each element to avoid overplotting Set legend type for each aesthetic: colorbar, legend,
na.value = "red") Also: rainbow(), heat.colors(),
f + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x), or none (no legend)
method = "rq")
topo.colors(), cm.colors(), Each position adjustment can be recast as a function
RColorBrewer::brewer.pal() with manual width and height arguments t + scale_fill_discrete(name = "Title",
x, y | ..quantile.., ..x.., ..y.. labels = c("A", "B", "C"))
f + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80, Shape scales Manual Shape values
Manual shape values
s + geom_bar(position = position_dodge(width = 1)) Set legend title and labels with a scale function.
fullrange = FALSE, level = 0.95)
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. p <- f + geom_point(
aes(shape = fl))
0 6 12 18 24 00
3 9 15 21 . | 100
t + coord_cartesian(
count
values = c(3:7)) 4 10 16 22 o %
with grid lines
0
no gridlines
ggplot() + stat_qq(aes(sample=1:100), distribution = qt,
0
c d e p r
c d e p r
count