Search code examples
rggplot2data-visualizationscatter-plot

Adding Title to ggplot from the dataset itself


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


Solution

  • 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.