Adding a calculation to the title of a ggplot

380 Views Asked by At

I'm new to R and wondering if the following is possible to calculation in the title of a ggplot scatter. The code below is how I thought it might be possible.

AlexPlot + ggtitle("Alex's BG, The average is " + mean(Alex$bg, na.rm = TRUE))
1

There are 1 best solutions below

0
M-- On BEST ANSWER

Since you haven't shared your data, I am using mpg dataset; you need to wrap the text and the numeric calculation within paste function. The comment above works as well, but I am not sure why we need to use paste0 twice!

library(ggplot2)

ggplot(mpg) + 
  geom_point(aes(hwy, displ)) +
  ggtitle(paste("Average mpg is", round(mean(mpg$hwy, na.rm = TRUE),2)))

As you can see, this works. You need to share a reproducible example of your data, if you get an error related to your specific data.