Home > Enterprise >  How to position plot.tag and plot.title side-by-side, on the same line
How to position plot.tag and plot.title side-by-side, on the same line

Time:03-10

I have created a custom ggplot theme, and would like to position the plot.tag and plot.title next to each other, on the same line. I want to keep the two labels unique from each other as I require different text formats. I also want to keep the tag optional, so if it's not specified in labs(), then the title will be shown by itself in the top-left position.

I've tried: plot.tag.position = 'topleft' but this creates unwanted space to the left of the plot; and plot.tag.position = c(0,1) but this overlaps the tag and title labels (in the code below, I've used this but hacked the title label with spaces).

library(ggplot2)

ggplot(economics, aes(x = date, y = uempmed))  
  geom_line()  
  labs(title = "                    Median duration of unemployment",
       tag = "Figure 1.0:",
       y = "Weeks")   
  theme(plot.title.position = 'plot', 
        plot.title = element_text(hjust = 0, vjust = 1, margin = margin(t = 0, r = 0, b = 0, l = 0, unit = 'mm')),
        plot.tag.position = c(0,1), 
        plot.tag = element_text(face = 'bold', hjust = 0, vjust = 1, margin = margin(t = 0, r = 0, b = 0, l = 0, unit = 'mm')))

This is the result that I'm aiming for: This is the result that I'm aiming for

CodePudding user response:

One option to achieve your desired result would be the ggtext package which allows you to glue the tag and the title together but still have the option to add different styles via some markdown or HTML/CSS. To make this a bit more convenient I make use of a helper function:

library(ggplot2)
library(ggtext)

labs2 <- function(title = NULL, tag = NULL, ...) {
  if (!is.null(tag)) {
    tag <- paste0("**", tag, "**")
    title <- paste(tag, title)
  }
  labs(title = title, ...)
}

ggplot(economics, aes(x = date, y = uempmed))  
  geom_line()  
  labs2(title = "Median duration of unemployment",
       tag = "Figure 1.0:",
       y = "Weeks")   
  theme(plot.title.position = 'plot', 
        plot.title = ggtext::element_markdown(hjust = 0, vjust = 1, margin = margin(t = 0, r = 0, b = 0, l = 0, unit = 'mm')))

  • Related