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
R
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
chartand use the<-assignment operator for storing the graph in thechartobject. We initialize a newggplotobject with theggplot()function and pass the name of theCars93dataset. Using the+operator, we add a layer to theggplotobject. - Line 2: We use the
geom_point()function to create a scatter plot where we use theaes()function for mapping theHorsepowervariable to the x-axis andPricevariable to the y-axis. - Line 3: We group the data by variable
Originusing thecolorargument and change the size of points to3using thesizeargument. - 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
Ask