PM 566: Introduction to Health Data Science
These slides were originally developed by Meredith Franklin (and Paul Marjoram) and modified by George G. Vega Yon and Kelly Street.
This lecture provides an introduction to R’s basic plotting functions as well as the ggplot2
package.
This section is based on chapter 3 of “R for Data Science”
ggplot2
is part of the Tidyverse. The tidyverse is…“an opinionated collection of R packages designed for data science. All packages share an underlying design philosophy, grammar, and data structures.” (https://www.tidyverse.org/)
ggplot2
is designed on the principle of adding layers.
ggplot()
ggplot()
is the dataset to use in the graphggplot()
with +
geom
functions such as point, lines, etcgeom
function takes a mapping
argument, which is always paired with aes()
aes()
mapping takes the x and y axes of the plotContinuing with the weather data from last week, let’s take the daily averages at each site, keeping some of the variables.
# Reading the data, filtering, and replacing NAs
met <- fread(file.path('..','03-exploratory','met_all.gz'))
met <- met[met$temp > -10][elev == 9999.0, elev := NA]
# Creating a smaller version of the dataset, averaged by day and weather station
met_avg <- met[,.(
temp = mean(temp,na.rm=TRUE),
rh = mean(rh,na.rm=TRUE),
wind.sp = mean(wind.sp,na.rm=TRUE),
vis.dist = mean(vis.dist,na.rm=TRUE),
lat = mean(lat),
lon = mean(lon),
elev = mean(elev,na.rm=TRUE)
), by=c("USAFID", "day")]
Let’s also create a new variable for region (east and west), categorize elevation, and create a multi-category variable for visibility for exploratory purposes.
# New sets of variables using "fast" ifelse from data.table
met_avg[, region := fifelse(lon > -98, "east", "west")]
met_avg[, elev_cat := fifelse(elev > 252, "high", "low")]
# Using the CUT function to create categories within the ranges
met_avg[, vis_cat := cut(
x = vis.dist,
breaks = c(0, 1000, 6000, 10000, Inf),
labels = c("fog", "mist", "haze", "clear"),
right = FALSE
)]
The variables we will focus on for this example are temp and rh (temperature in C and relative humidity %)
Here’s how to create a basic plot in ggplot2
We see that as temperature increases, relative humidity decreases.
geom_point()
adds a layer of points to your plot, to create a scatterplot.ggplot2
comes with many geom functions that each add a different type of layer to a plot.ggplot2
takes a mapping argument. This defines how variables in your dataset are mapped to visual properties.aes()
, and the x and y arguments of aes()
specify which variables to map to the x and y axes. ggplot2 looks for the mapped variables in the data argument, in this case, met_avg+
in the wrong place: it has to come at the end of the line, not the start.You can map the colors of your points to the class variable to reveal the region of data (west or east). In base plot, we need to convert the “character” variable into a “factor” variable in order to color by it.
We see that humidity in the east is generally higher than in the west and that the hottest temperatures are in the west.
Alternatively, ggplot2
can color by a “character” variable and adds a legend automatically.
The base plot alternative is to use the alpha
function from the scales
package.
Note that, by default, ggplot uses up to 6 shapes. If there are more, some of your data is not plotted!! (At least it warns you.) In base plot, point shape is controlled by the pch
(“plotting character”) argument.
To control aesthetics manually, set the aesthetic by name as an argument of your geom function; i.e. it goes outside of aes().
Equivalent to col = "blue"
in base plot.
code | description |
---|---|
x | position on x-axis |
y | position on y-axis |
shape | shape |
color | color of element borders |
fill | color inside of elements |
size | size |
alpha | transparency |
linetype | type of line |
code | description |
---|---|
first arg / x | position on x-axis |
second arg / y | position on y-axis |
pch | shape |
col | color of element borders |
fill | color inside of elements |
cex | size |
scales::alpha | transparency |
lty | type of line |
With base plot, you can add points to an existing plot with points()
, which takes the same arguments as plot()
for plotting points.
Facets are particularly useful for categorical variables and ggplot
makes them quite easy.
Or you can facet on two variables…
Base plot is not good at this! You can make multiple plots within a single plotting window by utilizing the layout()
function, but you will still have to make each plot manually.
Geometric objects are used to control the type of plot you draw. So far we have used scatterplots (via geom_point
). But now let’s try plotting a smoothed line fitted to the data (and note how we do side-by-side plots)
cowplot
is a package due to Claus Wilke, it “… is a simple add-on to ggplot
. It provides various features that help with creating publication-quality figures, such as a set of themes, functions to align plots and arrange them into complex compound figures, and functions that make it easy to annotate plots and or mix plots with images.”
Although ggplot
glosses over it, the smoothed line is fit by LOESS regression. So plotting one in base plot requires some additional code beforehand:
Note the lines
function, which adds lines to an existing plot. We have to order the values, because otherwise they remain in the same (unsorted) order as the original dataset.
Note that not every aesthetic works with every geom function. But now there are some new ones we can use.
Here we make the line type depend on the region and we clearly see east
has higher rh
than west
, but generally as temperatures increase, humidity decreases in both regions.
Histograms
Histograms
Boxplots
Boxplots
Lineplots
Just as you can add points to an existing plot, you can also add lines()
Lineplots
Polygons
Polygons
To plot this map data with baseplot, we have to use the range
trick to set up the plot first:
Note the argument asp = 1
which sets the correct aspect ratio of 1:1.
ggplot2 provides over 40 geoms, and extension packages provide even more (see https://ggplot2.tidyverse.org/reference/ for a sampling).
The best way to get a comprehensive overview is the ggplot2 cheatsheet, which you can find at https://github.com/rstudio/cheatsheets/blob/main/data-visualization-2.1.pdf
Let’s layer geoms
We can avoid repetition of aesthetics by passing a set of mappings to ggplot(). ggplot2 will treat these mappings as global mappings that apply to each geom in the graph.
geom_smooth()
has options. For example if we want a linear regression line we add method=lm
If you place mappings in a geom function, ggplot2
will use these mappings to extend or overwrite the global mappings for that layer only. This makes it possible to display different aesthetics in different layers.
You can use the same idea to specify different data for each layer. Here, our smooth line displays the full met dataset but the points are colored by visibilty.
Let’s say we want to know the frequencies of the different visibility categories.
The algorithm uses a built-in statistical transformation, called a “stat”, to calculate the counts.
You can over-ride the stat a geom uses to construct its plot. e.g., if we want to plpot proportions, rather than counts:
You can colour a bar chart using either the colour aesthetic, or, more usefully, fill:
More interestingly, you can fill by another variable (here, ‘region’). We also show that we can change the color scale.
position = "dodge"
places overlapping objects directly beside one another. This makes it easier to compare individual values.
You might want to draw greater attention to the statistical transformation in your code. For example, you might use stat_summary(), which summarizes the y values for each unique x value, to draw attention to the summary that you’re computing:
An option that can be very useful is position = "jitter"
. This adds a small amount of random noise to each point. This spreads out points that might otherwise be overlapping.
An option that can be very useful is position = "jitter"
. This adds a small amount of random noise to each point. This spreads out points that might otherwise be overlapping.
Coordinate systems are one of the more complicated corners of ggplot. To start with something simple, here’s how to flip axes:
There is also the ability to control the aspect ratio using coord_quickmap()
and to use polar coordinates with coord_polar()
.
ggplot(met_avg[!is.na(region)]) +
geom_point(aes(temp, rh, color = region)) +
labs(title = "Weather Station Data",x = expression("Temperature"*~degree*C), y = "Relative Humidity")+
scale_color_manual(name="Region", labels=c("East", "West"), values=c("east"="lightblue", "west"="purple"))+
theme_bw(base_family = "Times")
A great (comprehensive) reference for everything you can do with ggplot2 is the R Graphics Cookbook:
A briefer summary can be found here:
https://github.com/rstudio/cheatsheets/blob/main/data-visualization-2.1.pdf
Rstudio has a variety of other great Cheatsheets.
Let’s create a map of monthly average temperatures at each of the weather stations and colour the points by a temperature gradient. We need to create a colour palette and we can add a legend.
library(leaflet)
met_avg2 <- met[,.(temp = mean(temp,na.rm=TRUE), lat = mean(lat), lon = mean(lon)), by=c("USAFID")]
met_avg2 <- met_avg2[!is.na(temp)]
# Generating a color palette
temp.pal <- colorNumeric(c('darkgreen','goldenrod','brown'), domain=met_avg2$temp)
temp.pal
function (x)
{
if (length(x) == 0 || all(is.na(x))) {
return(pf(x))
}
if (is.null(rng))
rng <- range(x, na.rm = TRUE)
rescaled <- scales::rescale(x, from = rng)
if (any(rescaled < 0 | rescaled > 1, na.rm = TRUE))
warning("Some values were outside the color scale and will be treated as NA")
if (reverse) {
rescaled <- 1 - rescaled
}
pf(rescaled)
}
<bytecode: 0x7fc652072ac8>
<environment: 0x7fc6520750b0>
attr(,"colorType")
[1] "numeric"
attr(,"colorArgs")
attr(,"colorArgs")$na.color
[1] "#808080"
For the tile providers, take a look at this site: https://leaflet-extras.github.io/leaflet-providers/preview/
tempmap <- leaflet(met_avg2) |>
# The looks of the Map
addProviderTiles('CartoDB.Positron') |>
# Some circles
addCircles(
lat = ~lat, lng=~lon,
# HERE IS OUR PAL!
label = ~paste0(round(temp,2), ' C'), color = ~ temp.pal(temp),
opacity = 1, fillOpacity = 1, radius = 500
) |>
# And a pretty legend
addLegend('bottomleft', pal=temp.pal, values=met_avg2$temp,
title='Temperature, C', opacity=1)