Adding Titles and Subtitles to Plots with ggplot2
Learn how to add titles and subtitles to plots in ggplot2.
Introduction to titles and subtitles in ggplot2
When creating a plot with ggplot2
, adding a title and subtitle can provide context and clarity for the reader. The title can give an overview of the plotted main variables, while the subtitle can provide additional details. It is essential to choose a title and subtitle that accurately and concisely describes the plot’s content and provides enough information for the reader to understand the plot without being too long or complex.
Let’s first create a basic scatter plot using the Cars93
dataset and save it in an object called chart
. Then, we can add a title and subtitle to this plot.
Press + to interact
chart <- ggplot(Cars93) +geom_point(aes(x = Horsepower, y = Price,color = Origin),size = 3)+scale_color_manual(values = c("#03045E","#5DA9E9"))+theme_bw()chart
- Line 1: We create a new object named
chart
and use the<-
assignment operator for storing the graph in thechart
object. We initialize a newggplot
object with theggplot()
function and pass the name of theCars93
dataset. Using the+
operator, we add a layer to theggplot
object. - Line 2: We use the
geom_point()
function to create a scatter plot where we use theaes()
function for mapping theHorsepower
variable to the x-axis andPrice
variable to the y-axis. - Line 3: We group the data by variable
Origin
using thecolor
argument and change the size of points to3
using thesize
argument. - Line 4: We use the
scale_color_manual()
function to specify different colors for the scatter plot. - Line 5: We use the
theme_bw()
function for changing the default gray theme