Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...