Benjamin Schwetz
Benjamin Schwetz

Reputation: 643

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)

Upvotes: 8

Views: 8257

Answers (1)

user12117520
user12117520

Reputation: 166

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))

Upvotes: 14

Related Questions