1

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))
M--
  • 25,431
  • 8
  • 61
  • 93
  • 3
    Try `ggtitle(paste0("Alex's BG, The average is ", paste0(mean(Alex$bg, na.rm = TRUE))))` – Jamie Nov 22 '22 at 17:54
  • Thank you but recived error "Error in +ggtitle(paste0("Alex's BG, The average is ", paste0(mean(Alex$bg, : invalid argument to unary operator" – Kevin Cranfield Nov 22 '22 at 17:59
  • Please post the rest of your code or something that is reproducible. That error is likely due to something else. ie. you may have too many `+` or are using them in the wrong place – Jamie Nov 22 '22 at 18:03
  • sorry I must have miss-typed tried again and it worked thank you – Kevin Cranfield Nov 22 '22 at 18:09

1 Answers1

1

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.

M--
  • 25,431
  • 8
  • 61
  • 93