How To Add A Title To A Graph In R Ggplot2

Adding a title to a graph in R ggplot2 can help provide context to your data visualization. In this tutorial, we will go through the steps to add a title to a plot using the ggplot2 package in R.

Step 1: Load the ggplot2 library

Before we can create a plot and add a title, we need to load the ggplot2 library in R.

Step 2: Create a plot

Now, we can create a plot using the ggplot function. For this tutorial, we will use the built-in mpg dataset in R.

The mpg dataset contains fuel economy data for various car models, including the manufacturer, model, year, class, and miles per gallon for city and highway driving. When you create a plot using ggplot2 and specify the data argument as mpg, you are telling R to use the mpg dataset as the data source for the plot.

This code creates a boxplot of highway miles per gallon (hwy) by class using the mpg dataset.

Step 3: Add a title

To add a title to the plot, we can use the ggtitle function within the ggplot object.

This code adds the title “Highway Miles Per Gallon by Class” to our plot.

Conclusion

Adding a title to a graph in R ggplot2 is a simple but important step to provide context to your data visualization. With the ggtitle function, you can easily customize the title of your plot to suit your needs.

Code:

## Warning: Removed rows containing non-finite values (stat_boxplot).