Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change font size for all text in a ggplot object relative to current value?

When creating plots using ggplot2, I often encounter the following:

I have twitched all the text using element_text(size=<value>), so it looks good in my report, but to use it in another context, I need to update the size of all text (make it bigger or smaller), to keep the plot readable.

Is there a way to update font size for all text elements, without having to explicitly specifying the elements, i.e. not

theme_update(
       axis.text=element_text(size=12),
       axis.title=element_text(size=14),
       ...
)

Reprex

library(ggplot2)
p <- ggplot(iris) +
  aes(Sepal.Width, Sepal.Length, color = Species)+
  geom_point()+
  ggtitle(
    "All text",
    "should be 50% larger"
  ) +
  theme_bw()
p

Created on 2019-09-25 by the reprex package (v0.3.0)

like image 796
Benjamin Schwetz Avatar asked Sep 25 '19 07:09

Benjamin Schwetz


1 Answers

ggplot objects are displayed through grid graphics, and grid graphics inherit the parent viewport's cex setting as a multiplier,

print(p, vp=grid::viewport(gp=grid::gpar(cex=2)))

or (to only affect the theme elements, but won't affect e.g. geom_text layers),

p + theme(text=element_text(size=24))
like image 130
user12117520 Avatar answered Nov 14 '22 21:11

user12117520