rggplot2ggtitle

How to change the chart title dynamically in R?


Here is an example using mtcars to split by a variable into separate plots. What I created is a scatter plot of vs and mpg by splitting the data set by cyl. First an empty list is created. Then I used lapply to loop through the values of cyl (4,6,8) and then filter the data by that value. After that I plotted the scatter plot for the subset and saved it to the empty list.

library(dplyr)
library(ggplot2)
gglist <- list()

gglist <- lapply(c(4,6,8), function(x){
    
    ggplot(filter(mtcars, cyl == x))+
        geom_point(aes(x=vs,y=mpg))+
        labs(title = "Relationship between vs and mpg based on the respective cyl")
})
gglist

The output returns three scatter plots with the title "Relationship between vs and mpg based on the respective cyl". However I wish to dynamically change the title of each scatter plot based on the unique value of cyl.

unique(mtcars$cyl)
#[1] 6 4 8

Expected output of various chart titles is as folllows.

#"Relationship between vs and mpg when cyl is 4"
#"Relationship between vs and mpg when cyl is 6"
#"Relationship between vs and mpg when cyl is 8"

 

Solution

  • You can use paste or paste0 to concatenate strings and then use that as the title:

    gglist <- lapply(c(4,6,8), function(x){
      
      ggplot(filter(mtcars, cyl == x))+
        geom_point(aes(x=vs,y=mpg))+
        labs(title = paste("Relationship between vs and mpg when cyl is ", x))
    })
    gglist