Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different font sizes for different portions of text in ggplot2 title

Tags:

r

ggplot2

ggtext

Consider the following graph:

require(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() +
  labs(title = 'Iris[small font]' ) +
  theme_classic()

enter image description here

The Left graph is the code output, the right graph shows the desired result, I used Adobe Illustrator for that

The question is, if it is possible to change the font size in line, in this example the "[small font]" label in the title, but of course it is a general question also regarding other labels such as for the axes and legend etc.

Obviously, the font size is set with theme(). However, there might be a way setting a "relative font size", e.g. using rel() and using this somehow with a labeller function??

like image 830
tjebo Avatar asked Oct 17 '18 10:10

tjebo


2 Answers

You can avoid the fiddling with grid grobs if you use the package ggtext instead.

# this requires the current development versions of ggplot2 and ggtext
# remotes::install_github("tidyverse/ggplot2")
# remotes::install_github("clauswilke/ggtext")

library(ggplot2)
library(ggtext)

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point() +
  ggtitle("<span style='font-size:20pt'>Iris </span><span style='font-size:12pt'>[some text]</span>") +
  theme(
    plot.title = element_markdown()
  )

Created on 2019-12-03 by the reprex package (v0.3.0)

like image 30
Claus Wilke Avatar answered Oct 06 '22 00:10

Claus Wilke


library(grid)
library(gridtext) # devtools::install_github("clauswilke/gridtext")
library(gridExtra)
library(ggplot2)

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point() +
  labs(title = "Replace-able") -> gg

gb <- ggplot_build(gg)
gt <- ggplot_gtable(gb)

title <- "<span style='font-size:20'>Iris </span><span style='font-size:12'>[some text]</span>"
tg <- rich_text_grob(title, x = unit(0, "lines"), y = unit(2, "lines"))

gt$grobs[[16]] <- tg

grid.newpage()
grid.draw(gt)

enter image description here

Then, there's:

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point() -> gg

title <- "<span style='font-size:20'>Iris </span><span style='font-size:12'>[some text]</span>"
tg <- rich_text_grob(title, x = unit(2, "lines"), y = unit(2, "lines"))

grid.newpage()
grid.draw(
  arrangeGrob(tg, gg, heights=c(0.1, 0.8))
)

enter image description here

like image 197
hrbrmstr Avatar answered Oct 06 '22 00:10

hrbrmstr