




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to using the ggplot2 package in R for creating complex graphs. It covers the basics of setting up a plot, adding geoms such as histograms and density plots, customizing graph appearance with themes, and representing variables with different colors and shapes. The document also includes exercises for practicing these skills using the ChickWeight and iris datasets.
Typology: Schemes and Mind Maps
1 / 8
This page cannot be seen from the preview
Don't miss anything!





The ggplot2 package allows you to build very complex graphs layer by layer. Unlike graphs we construct using the base functions in R, ggplot2 takes care of details like legends and choice of plotting symbols automatically, although you can customize these choices if you wish. A handy cheatsheet which summarizes the commands available in ggplot2 can be downloaded here www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf.
Using the ggplot2 suite of functions you start a graphic using the ggplot() command. This command does not display anything until you add a ‘geom’ command; it just sets up the scaffolding for the plot. The syntax of ggplot() is
ggplot(data = NULL, mapping = aes(x, y, ))
The data argument is the dataframe containing the variables you want to graph. It must be an object of type dataframe.
The x argument is set equal to the variable in your data you wish to be represented on the x-axis. The y argument will be the variable represented on the y-axis.
You can map additional variables in your dataset to plot attributes like color or size of plotting symbol, by simply adding an argument like color=gender within aes().
You add (literally, using a + sign) a ’geom’ to ggplot() such as geom_histogram() or geom_dotplot() to choose the type of graph which will display the data. Let’s obtain a histogram of mpg in the mtcars dataframe.
> library(ggplot2) > class(mtcars) #verify mtcars is a dataframe
[1] "data.frame"
> # sets up the plot, but does not produce a graph yet > p0 <- ggplot(data=mtcars, aes(x=mpg)) > #now get the graph > p0+geom_histogram()
0
1
2
3
4
10 15 20 25 30 35
Let’s customize the graph. There are different ‘themes’ which determine the setup of the plot area, i.e. whether gridlines are shown and the colors of gridlines and the background. See the cheatsheet, page 2, bottom right for a few choices. You can choose the fill and outline colors.
> p0 <- ggplot(data=mtcars, aes(x=mpg)) > p0+geom_histogram(fill="yellow", color="red")+theme_minimal() #ugliest graph ever!
100
200
300
10 15 20 25 30 35
4 6 8
0 1
Exercise:
> chick.sub <- subset(ChickWeight, Time==21)
Graph a smoothed density of the mpg for each ’cyl’ category and choose a specific color palette. To see color palette choices, load the RColorBrewer package and type display.brewer.all().
> p1 <- ggplot(data=mtcars,aes(x=mpg)) > p2 = p1+ggtitle("Miles per Gallon by Number of Cylinders") > p3 = p2+geom_density(aes(group=cyl,fill=cyl),color='white', alpha=0.3) > p4 = p3+theme_classic()+scale_fill_brewer(palette="PuRd") > p > #alpha sets the transparency of the fill color
10 15 20 25 30 35
4 6 8
Miles per Gallon by Number of Cylinders
Exercise: Using the ChickWeight data, produce separate smoothed density graphs of weights at time 21 by Diet.
Adding Layers
> p1 <- ggplot(data=mtcars,aes(x=mpg,y=disp,color=cyl)) > p1+geom_point()+geom_smooth(method='lm') > > # the default method in geom_smooth overfits the data, IMO > # pl+ geom_point()+geom_smooth()
10 15 20 25 30 3510 15 20 25 30 3510 15 20 25 30 35
100
200
300
400
3 4 5
Exercise: Using the iris data, obtain a scatterplot of x=Petal.Length vs. y=Petal.Width. Facet by Species.
A graph of longitudinal data (each subject is observed repeatedly over time) for the ChickWeight dataset.
> my.data.summary <- plyr::ddply(ChickWeight, c('Time', 'Diet') ,
100
200
0 5 10 15 20
1 2 3 4
How to use the ggplot2 cheatsheet examples
The examples use datasets included with the ggplot2 package. Worth through the geom line() example.