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.
1 |
library(ggplot2) |
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.
1 2 |
mpg_plot <- ggplot(data = mpg, aes(x = class, y = hwy)) + geom_boxplot() |
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.
1 |
mpg_plot + ggtitle("Highway Miles Per Gallon by Class") |
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:
1 2 3 4 5 6 |
library(ggplot2) mpg_plot <- ggplot(data = mpg, aes(x = class, y = hwy)) + geom_boxplot() mpg_plot + ggtitle("Highway Miles Per Gallon by Class") |
## Warning: Removed rows containing non-finite values (stat_boxplot).