paste function in ggtitle: remove extra spaces and add a new line in ggplot title

995 Views Asked by At

Within the shiny context, how can I remove extra space after and before parentheses in the title of a plot? As shown in the below image, there are redundant spaces between "(" and "6" as well as between "+" and ")".

Also, I was wondering how can I break down the title in such a way that the county name as well as the age group appear in the next line.

enter image description here

Here is my code:

ggtitle(
    paste(
      "Percentage of Population Living with and Responsible for Grandchildren in", 
      input$county_grandpa,
      "(",
      input$Age_Group_grandpa,
     ")"
    ) 
  )
1

There are 1 best solutions below

0
M-- On BEST ANSWER

This should do the job for you. paste0 doesn't have sep = " " like paste and \n adds a new line. Add theme if you want the text to be centered.

ggtitle(
    paste0(
      "Percentage of Population Living with and Responsible for Grandchildren in \n",
      input$county_grandpa,
      " (",
      input$Age_Group_grandpa,
     ")"
    ) 
  ) +
  theme(plot.title = element_text(hjust = 0.5))