University of Strathclyde
2025-11-04
R packages
CRANCRAN - the Comprehensive R Archive Network: https://cran.r-project.org/
Figure 2: How scientists see the same data may vary by field
What is ggplot2?
ggplot2 is the graphics packageFour pillars of ggplot2
geomsYou can use ggplot2 like R’s base graphics
qplot() ≈ plot()
Plot aesthetics
qplot()
Plot geoms
geom (short for geometry) defines the “type” of representation
Figure 6: Some ggplot2 geom types
We’ve just used another Grammar of Graphics concept: layers
ggplot2 plots are built as layersgeomData and aesthetics can be defined in a base ggplot object
Figure 7: Defining aesthetics in a ggplot2 base layer
Data and aesthetics can be defined in a base ggplot object
Figure 8: Overriding aesthetics of a ggplot2 base layer
INTERACTIVE DEMO
We use several layers of geoms to build up a plot
alpha controls opacity for a layerp <- ggplot(data=gapminder, aes(x=lifeExp, y=gdpPercap, color=continent))
p + geom_line(aes(group=country)) + geom_point(alpha=0.4)
Figure 9: ggplot2 figures are built by adding layers
INTERACTIVE DEMO
Create a figure showing how life expectancy changes as a function of time
scalesData transformations are handled with scale layers
Figure 10: Axis scales, palette scales, etc. are added as layers
INTERACTIVE DEMO
Some geom layers transform the dataset
Figure 11: Statistical transformations are also added as layers
INTERACTIVE DEMO
Comparisons can be clearer with multiple panels
Use the facet_wrap() layer to generate grids of plots
Create a scatterplot and contour densities of GDP per capita against population size
ADVANCED CHALLENGE
Transform the x axis to better visualise data spread, and use facets to panel density plots by year.
What is literate programming?
R Markdown files embody Literate Programming
File \(\rightarrow\) New File \(\rightarrow\) R Markdown.Rmd)R Markdown 1R Markdown 2Executable R code
R code is fenced by backticks (```)Click on Knit
INTERACTIVE DEMO
R Markdown report on the gapminder dataFigure 14: R Markdown output
R Markdown documentation: http://rmarkdown.rstudio.com/R Markdown cheat sheet: http://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdfR Markdown: https://www.rstudio.com/resources/webinars/getting-started-with-r-markdown/R, RStudio and how to set up a projectR and produce summary statistics and plots with base toolsR, the most important data structuresRWELL DONE!!
Figure 17: R is a rollercoaster
IBioIC Carpentries Workshop