How to Get Started with ggplot2 in R

05.17.2021

Intro

The library ggplot extends the normal graphics library in R greatly. At first, the syntax can seem a bit odd as it chains together function with the addition operator, +. However, you may come to see that the separate is very intuitive and easy to use. In this article, we will learn how to get started with ggplot2.

The first thing we want to do is install the library. If you don’t have it installed, run the following command. This will actually install the full tidyverse library which is a widely used package. Simply uncomment the line below and run it to install.

# install.packages("tidyverse")

Then, we can load the library, we can do the following.

library(ggplot2)

To create a plot in ggplot2, you start with the ggplot which has the following signature. ggplot(dataframe, aes).

The aes is another function you will use. It is called an aesthetics which will use to map our data and to set details like color and size. The basic example is aes(x, y)

Okay, let’s see how this all comes together. We can use the built in mpg data set which is loaded for us.

library(ggplot2)

ggplot(mpg, aes(displ, hwy))

unnamed chunk 3 1

In the example above, we created a ggplot with the data frame, mpg. Our x is displ and our y is hwy. Now this wont’ display anything yet. To display, we need to add a layer. The first layer we will learn is a scatter plot or point layer. We use the geom_point (geometric point) function. The tricky part is we use the + operator to add to our ggplot above.

library(ggplot2)

ggplot(mpg, aes(displ, hwy)) + 
  geom_point()

unnamed chunk 4 1

Now, we have created our first plot in ggplot. That’s a lot to read to understand, but once you have these basics down, you will start to learn the magic of ggplot.