ggplot2
University of Oxford
ggplot2
- A Grammar of Graphicsggplot2
makes it easy to create beautiful graphics with minimal effort.ggplot2
?ggplot2
and dplyr
are part of the tidyverse
install.packages('tidyverse')
library(tidyverse)
ggplot2
referencesggplot2
syntax takes a bit of getting used to+
rather than |>
gapminder
dataset+
with |>
pop
on the x-axis and lifeExp
on the y-axis, based on gapminder_2007
.gdpPercap
on the y-axis.Label your axes and give each plot a title!
pop
on the x-axis and lifeExp
on the y-axis using gapminder_2007
.gdpPercap
in levels and lifeExp
in logs.ggplot2
Syntax Basicsmapping = aes(x = gdpPerCap, y = lifeExp)
aes
is short for aestheticgdpPerCap
to the x-coordinatelifeExp
to the y-coordinategeom_point()
is a geometric object, geom for short
color
Aestheticsize
AestheticWould it make sense to set size = continent
? What about setting col = pop
?
Using gapminder
data from 1952, plot life expectancy on the y-axis and log population on the x-axis. Color the points by continent.
gapminder
data from 1997. Facet by continent and put GDP/capita on the log scale on the x-axis and life expectancy on the y-axis. Indicate population by the size of each point.pop
rather than year? Why?geom_line()
expand_limits(y = 0)
to the previous plot. What happens? Why and when might this be helpful?gapminder
on the y-axis and year
on the x-axis.geom_histogram()
x
. Why?binwidth
binwidth
? Try it and find out!geom_boxplot()
x
for the groups; y
for the variable that is summarizedUse faceting to construct a collection of boxplots, each of which compares log GDP/capita across continents in a given year.
geom_col()
The x
argument of aes
must be categorical
coord_flip()
Go back and turn your boxplots from the last exercise sideways to make it easier to read the continent labels.
Make a collection of bar plots faceted by year that compare mean GDP per capita across countries in a given year. Orient your plots so it’s easy to read the continent labels.
Bar charts are inferior to Cleveland dot charts
meanLifeExp
See https://forcats.tidyverse.org/ for fct_reorder()
gapminder |>
filter(year %in% c(1987, 2007)) |>
mutate(year = factor(year)) |>
group_by(continent, year) |>
summarize(meanLifeExp = mean(lifeExp)) |>
ggplot(aes(x = meanLifeExp, y = continent)) +
geom_line(aes(group = continent)) +
geom_point(aes(color = year)) +
xlab('Average Life Expectancy') +
ylab('Continent') +
theme_bw()
Make a dot chart of GDP per capita in all European countries in the year 2007. Sort the dots so that the country with the highest GDP per capita appears a the top and the country with the lowest appears at the bottom.
ggsave()
ggsave(filename, width = , height = )
plot = SOMETHING
filename
is the path and file name.jpg
, .png
, .pdf
and many othersggplot2
later this term.