Set Up Your Project and Load Libraries

To begin we must load some libraries we will be using. If we do not load them, R will not be able to find the functions contained in these libraries. Right now we’re just using the gapminder, socviz, and ggplot2 packages.

Get Started

The fastest, but not the smartest way to start is to use plot from the base R language.

gapminder
## # A tibble: 1,704 x 6
##    country     continent  year lifeExp      pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Afghanistan Asia       1952    28.8  8425333      779.
##  2 Afghanistan Asia       1957    30.3  9240934      821.
##  3 Afghanistan Asia       1962    32.0 10267083      853.
##  4 Afghanistan Asia       1967    34.0 11537966      836.
##  5 Afghanistan Asia       1972    36.1 13079460      740.
##  6 Afghanistan Asia       1977    38.4 14880372      786.
##  7 Afghanistan Asia       1982    39.9 12881816      978.
##  8 Afghanistan Asia       1987    40.8 13867957      852.
##  9 Afghanistan Asia       1992    41.7 16317921      649.
## 10 Afghanistan Asia       1997    41.8 22227415      635.
## # … with 1,694 more rows
plot(gapminder$gdpPercap,gapminder$lifeExp)

It does the job, but 1) the defaults aren’t always great, 2) it is ugly as sin, and 3) you have to remember an incomprehensible list of commands to get anything done.

Let’s quickly switch to ggplot2. We start with qplot, which can be used to make a quick plot that looks so much nicer than base R graphics.

qplot(data=gapminder,x=gdpPercap,y=lifeExp)

That’s the last time we’ll use qplot. It’s much prettier, but doesn’t let us behold the power of this fully operational battlestation, I mean ggplot2.

p <- ggplot(data=gapminder, mapping=aes(x=gdpPercap,y=lifeExp))
p2 <- p + geom_point()

You made your first plot with the real ggplot2!

Let’s save this plot in the Plots subfolder, with a set width and height. Notice we have to issue a save command for each file type we want.

We’ll want to save both PNG and PDF files. The PNG file is useful for display and sharing (eg on Twitter!). The PDF file is best for generating PDFs for ultimate use as presentations and papers that can be resized.

Save

ggsave(filename = "Plots/ch2_1.png",width=8,height=5)
ggsave(filename = "Plots/ch2_1.pdf",width=8,height=5)

Knit

Click the Knit button to create a knitted document fusing code, output, and notes together.