Last active
January 5, 2016 05:02
-
-
Save zoltanctoth/7134496 to your computer and use it in GitHub Desktop.
Learn ggplot2 by example. This tutorial is especially useful and easy to follow if you went through Hadley Wickham's article on the Layered Grammar of Graphics. https://www.dropbox.com/s/enzoi6b5yfwpvhm/layered-grammar.pdf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
# Take a look at our example dataset | |
head(diamonds) | |
# Make a chart from scratch | |
x = ggplot() + | |
layer( | |
data = diamonds, mapping = aes(x=carat,y=price), | |
stat='identity', position="identity", geom="point" | |
) + | |
scale_x_continuous() + | |
scale_y_continuous() + | |
coord_cartesian() | |
x | |
#TODO: Convert this into a jitter plot | |
ggplot() + | |
layer( | |
data = diamonds, mapping = aes(x=carat,y=price), | |
stat='identity', position="jitter", geom="point" | |
) + | |
scale_x_continuous() + | |
scale_y_continuous() + | |
coord_cartesian() | |
# Adding a regression layer | |
y = x + layer( | |
data = diamonds, mapping = aes(x=carat,y=price), | |
stat='smooth', position="identity", geom="smooth" | |
) | |
y | |
# TODO: Is this a power curve? | |
# add 1. y <- ..., and x and y log scale | |
y + scale_x_log10() + scale_y_log10() | |
# IDENTITITY TRANSFORMATIONS | |
# Build up the same with defaults, as follows: | |
# 1. Get rid of stat and position | |
# 2. Get rid of scales and coordinates | |
# All of these are good by default | |
ggplot() + | |
layer( | |
data = diamonds, mapping = aes(x=carat,y=price), | |
geom="point" | |
) + | |
layer( | |
data = diamonds, mapping = aes(x=carat,y=price), | |
geom="smooth" | |
) | |
# 3. get rid of layer definitintions | |
ggplot(data = diamonds, mapping = aes(x=carat,y=price)) + | |
geom_point() + geom_smooth() | |
# 4. switch to qplot | |
qplot(carat,price,data=diamonds,geom=c('point','smooth')) | |
# 5. log='xy' | |
qplot(carat,price,data=diamonds,geom=c('point','smooth'),log='xy') | |
# 6. Let's change the theme to bw | |
qplot(carat,price,data=diamonds,geom=c('point','smooth'),log='xy') + | |
theme_bw() | |
# A FEW EXTRA FEATURES | |
# TODO: Faceting | |
qplot(carat,price,data=diamonds,geom=c('point','smooth'),log='xy') + facet_grid(. ~ cut) | |
# TODO: Histogram by cut | |
qplot(cut,data=diamonds) | |
# TODO: Histogram as barchart | |
ggplot(diamonds,aes(x="",fill=cut)) + geom_bar(width=1) | |
# TODO: Pie Chart | |
ggplot(diamonds,aes(x="",fill=cut)) + geom_bar(width=1) + coord_polar(theta='y') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment