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.
Then, we can load the library, we can do the following.
To create a plot in ggplot2, you start with the
ggplot which has the
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
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))
In the example above, we created a ggplot with the data frame, mpg. Our
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
library(ggplot2) ggplot(mpg, aes(displ, hwy)) + geom_point()
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.