Show Menu
Cheatography

R plotting Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Plotting Process

0. Get data
1. Specify aesthetic (what fields being plot)
2. Add geoms (essentially type of plot)
3. Modify elements

Basic Plots

# qplot - includes a lot of defaults
qplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point")

# ggplot - allows more customisation
ggplot(data=mpg, aes(x=cty, y = hwy)) +
    geom_point(aes(color = cyl)) +
    geom_smooth(method = "lm") +
    coord_cartesian() +
    scale_color_gradient() +
    theme_bw()

One Variable

### NB requires a <- ggplot(data = mpg, aes(hwy))

# histogram
geom_histogram(binwidth = 5)

# density
geom_density()

# bar (categorical data)
geom_bar()

Two Variable

### NB need: f <- ggplot(mpg, aes(cty,hwy))

# dot / jitter - jitter deals with overlapping points
f + geom_jitter()
f + geom_point()

# quantile 
f + geom_quantile()

# smoothed / lm
f + geom_smooth(model=lm)

# line
f + geom_line()

# error bar
f + geom_errorbar()

# point range
f + geom_pointrange()
 

Modifiers

# scales - alpha, color, fill, linetype, shape, size
scale_*_continuous()
scale_*_discrete()
scale_*_identity()
scale_*_manual(values = c())
scale_x_date(labels=date_format("%m/%d"), breaks = date_breaks("2 weeks"))
scale_x_datetime()

# coordinate systems
coord_cartesian(xlim=c(0, 5), ylim=x(0,5))
coord_flip()
coord_trans(ytrans="sqrt")

# labels
ggtitle("title")
xlab("x")
ylab("y")
labs(title=, x=, y=)

# position adjustments
s + geom_bar(position = "dodge") # side by side
s + geom_bar(position = "stack") # stack
s + geom_bar(position = "fill") # stack, normalized height

# legends
theme(legend.position="bottom") # top, left, right
scale_fill_discrete(name= "title", labels=c("A", "B", "C"))

# color and fill scales
scale_fill_brewer(palette = "Blues")
scale_fill_gradient(low="red", high="yellow")

# themes 
theme_bw() # white background w/ gridlines

Faceting

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

# facet into cols
t + facet_grid(. ~ fl)

# facet into rows
t + facet_grid(year ~ .)

# facet into rows & cols
t + facet_grid(year ~ fl)

Other

library('repr')
options(repr.plot.width=5, repr.plot.height=4)
ggsave("plot.png", width = 5, height = 5)