Adding Title to ggplot from the dataset itself

Viewed 278

I am working with the R programming language. I made the following graph using the built-in "mtcars" dataset:

library(ggplot2)
a = ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("mtcars: wt vs mpg")

enter image description here

Question: Now, I am trying to customize the title, but I want the title to "contain a variable reference", for example:

b = ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("mtcars: wt vs mpg - average mpg = mean(mtcars$mpg)")

But this command literally just prints the code I wrote:

enter image description here

I know that the "mean" command runs by itself:

 mean(mtcars$mpg)
[1] 20.09062

But can someone please help me change this code:

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("mtcars: wt vs mpg - average mpg = mean(mtcars$mpg)")

So that it produces something like this (note: here, I manually wrote the "mean" by hand):

enter image description here

Thanks

3 Answers

You can do this using paste().

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle(paste0("mtcars: wt vs mpg - average mpg = ", mean(mtcars$mpg)))

If you need to you can add more text and variables with commas like so:

ggtitle(paste0('text ', var1, 'text2 etc ', var2, var3, 'text3'))

Note that paste0 is a variant of paste that concatenates things with no space or separator in between.

An option with glue

library(ggplot2)
library(glue)
ggplot(mtcars, aes(x = wt, y = mpg)) +
      geom_point() + 
      ggtitle(glue("mtcars: wt vs mpg - average mpg = {mean(mtcars$mpg)}"))

We could also use str_c from stringr package which is part of tidyverse package. str_c is equivalent to paste0

library(tidyverse)

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle(str_c("mtcars: wt vs mpg - average mpg = ", mean(mtcars$mpg)))

Related