Home > Software engineering >  Adding a calculation to the title of a ggplot
Adding a calculation to the title of a ggplot

Time:11-23

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))

CodePudding user response:

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.

  • Related