Home > Software design >  Vectorizing R expression
Vectorizing R expression

Time:08-21

I am trying to vectorize the title and subtitle of a figure within the R expression using atop() function as in the example below with no success. Could anyone help me with this?

title = "Text line 1"
subtitle = "Text line 2"

fig1 = ggplot(mtcars, aes(x = cyl, y = mpg)) geom_boxplot(stat = "boxplot")
fig2 = ggplot(mtcars, aes(x = cyl, y = mpg)) geom_point()
fg = ggarrange(fig1, fig2, ncol = 2, nrow = 1)

title <- expression(atop(title, scriptstyle(subtitle)))
annotate_figure(fg, top = text_grob(title, face = "bold", size = 14))

CodePudding user response:

Another option using expr with atop and assign !! before the variables like this:

library(ggplot2)
library(ggpubr)
title = "Text line 1"
subtitle = "Text line 2"

fig1 = ggplot(mtcars, aes(x = cyl, y = mpg)) geom_boxplot(stat = "boxplot")
fig2 = ggplot(mtcars, aes(x = cyl, y = mpg)) geom_point()
fg = ggarrange(fig1, fig2, ncol = 2, nrow = 1)

title <- expr(atop(!!title, scriptstyle(!!subtitle)))
annotate_figure(fg, top = text_grob(title, face = "bold", size = 14))

Created on 2022-08-21 with reprex v2.0.2

CodePudding user response:

Instead of expression use bquote. It allows for variable's evaluation.

library(ggplot2)
library(ggpubr)

title = "Text line 1"
subtitle = "Text line 2"

fig1 = ggplot(mtcars, aes(x = as.factor(cyl), y = mpg)) 
  geom_boxplot(stat = "boxplot")
fig2 = ggplot(mtcars, aes(x = cyl, y = mpg)) 
  geom_point()
fg = ggarrange(fig1, fig2, ncol = 2, nrow = 1)

maintitle <- bquote(atop(.(title), scriptstyle(.(subtitle))), 
                    list(title = title, subtitle = subtitle))
annotate_figure(fg, top = text_grob(maintitle, face = "bold", size = 14))

Created on 2022-08-21 by the reprex package (v2.0.1)

  • Related