0

I'd like to add a title (in one colour/size) and a subtitle (in a second colour/size) to a legend element in ggplot2, like this:

Title and subtitle

But the best I can do so far is:

Long multi-line title

using this code:

gg <- ggplot(sig_table, aes(x = x, y = y, col = neg_log_FP)) +
  geom_point(aes(size = as.numeric(percentage))) +
  xlab("Cohort") +
  ylab("Signature") +
  scale_color_continuous(low = "blue", high = "red", name = "-log(pval)", limits = c(0,3)) +
  scale_size(name = "Size of circle\nProportion of\nsamples within\ncohort", limits = c(0,100), range = c(0,12), 
             guide = guide_legend(override.aes=list(colour = "red"))) +
  scale_x_discrete(limits = xlabels, position = "top") +
  scale_y_discrete(limits = ylabels) +
  theme_bw()

Is there a way to change the size of the text "Proportion of samples within cohort" to a smaller font?

NB: (in edit), this is not a duplicate of increase legend font size ggplot2, because I want two different sizes in the legend text, not a uniform size.

user36196
  • 133
  • 11

1 Answers1

3

One option would be to use the ggtext package which allows for styling of text using some HTML, CSS or markdown and allows to set a smaller font size for just a word or a part of a string by wrapping in a <span> tag (Note: As we are dealing with HTML we have to use a <br> tag to add a line break.). Additionally this requires to set the theme element for the legend.title to ggtext::element_markdown().

Using some fake example data based on gapminder:

library(gapminder)
library(ggplot2)
library(ggtext)

ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, col = continent)) +
  geom_point(aes(size = pop)) +
  xlab("Cohort") +
  ylab("Signature") +
  scale_size(
    name = paste0(
      "Size of circle<br>",
      "<span style='font-size: 8pt'>",
      "Proportion of samples<br>within cohort</span>"
    ),
    range = c(0, 12),
    guide = guide_legend(
      override.aes = list(colour = "red")
    )
  ) +
  theme_bw() +
  theme(legend.title = ggtext::element_markdown())

stefan
  • 90,330
  • 6
  • 25
  • 51