The programming language R is popular among statisticians and mathematicians for mathematical computations and programming.
The language has many diverse libraries that help make a user’s programming journey easy. It also has built-in datasets that can be used for experimenting and learning.
The ggplot2
is one of R’s most popular libraries among others. The library is a practical and useful implementation of the “Grammar of Graphics book” in R and is used for data visualization and plotting charts. The ggplot2
is considered versatile because it allows for easy customization since we add the plot’s aesthetics, layer by layer.
There are two ways to install ggplot2
:
tidyverse
library. The ggplot2
package is contained within the tidyverse library, so installing it automatically installs ggplot2
.install.packages("tidyverse")
library(tidyverse)
ggplot2
library.install.packages("ggplot2")
library(ggplot2)
After we install and load the library, using either of the options shown above, the next step is to use the package.
We’ll need to invoke the ggplot()
function for this.
ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()
ggplot()
wraps together the data and the aesthetics needed.data
specifies the data file being used.mapping
specifies the variables being used to build the chart. These are x
and y
variables where needed.geom_function
can be any function such as geom_point
for scatterplots, geom_line
for line plots or even geom_boxplot
for boxplots.Let’s look at the code below:
library(tidyverse)ggplot(data = iris,mapping = aes(x = Sepal.Length, y = Sepal.Width)) +geom_point() +ggtitle("Sepal Width Vs Sepal Length") +theme(plot.title = element_text(hjust = 0.5)) +xlab("Length") +ylab("Width")
tidyverse
. The
ggplot2
can also be used here instead.geom_point()
.ggtitle()
.left_aligned
.Note: We can access the built-in datasets and their descriptions using the function
data()
.