Professional Documents
Culture Documents
Ggplot2 Cheatsheet PDF
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 qplot() or ggplot() g <- ggplot(economics, aes(date, unemploy))
x, y, alpha, color, fill, linetype, size 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
aesthetic mappings data geom 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,
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))
qplot(x = cty,Fy M = hwy, A color4 = cyl, data = 4mpg, geom = "point"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 Maps
gymax=unemploy
+ geom_path(lineend="butt", x, y, alpha, color, data e<-+data.frame(murder = USArrests$Murder,
Creates a complete plot2 with given data, 3 3
geom, and 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())
mappings. Supplies many + useful defaults. = 2 Discrete X, Discrete Y
map <- map_data("state")
shape, size
F MA
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()
04 04
e + geom_map(aes(map_id Maps = state), map = map) +
d<-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
Begins a plot that you finish by3 adding layers to. No yend = lat + delta_lat))
d<- ggplot(seals, aes(x d + geom_path(lineend="butt", Three Variables e + x, y,
geom_map(alpha, color,= state),
fill map = map) +
0 0
0 1 0 1 3 4 = long, y = lat)) h + geom_jitter() aes(map_id
defaults, butdata provides geom more control
4
than plotqplot().
2 2
coordinate
system linejoin="round’
x, xend, y, yend, alpha, color, 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,
dd++geom_rect(aes(xmin
geom_segment(aes(= long, ymin = lat,
x=F
alpha, color, fill, linetype, size
data y=A
xend =long long++delta_long,
delta_long, x, y, alpha, color,
i
linetype,
<- ggplot(seals,
size
aes(long, lat)) vjust=0.5, interpolate=FALSE) shape, size
add layers, ymax xmax=
yend == latlat ++ delta_lat))
delta_lat)) x, y, alpha, color, fill, linetype, size, weight
Three Variables x, y, alpha, fill
ggplot(mpg, aes(hwy, cty)) +
elements with + xmax, x, xend, y, yend, alpha, d +
color, geom_ribbon(
linetype,
xmin, ymax, ymin, alpha, color, fill, 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))
geom_point(aes(color = cyl)) + layer = 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,
geom_smooth(method ="lm") +
RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212
default stat + xmax= ymax
long + delta_long,
= lat + delta_lat))
• rstudio.com
x, ymax, ymin, alpha, color, fill, linetype, size 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)))
coord_cartesian() + layer specific xmax, xmin, ymax, ymin, alpha, color, fill,
i + geom_contour(aes(z = z)) i + geom_tile(aes(fill = z)) map <- map_data("state")
scale_color_gradient() + mappings 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))
theme_bw() additional l + geom_map(aes(map_id = state), map = map) +
elements
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
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 0.9.3.1 • Updated: 3/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
extras and strains 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", hight = "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