Frits Verstraten Frits Verstraten - 1 month ago 37
R Question

Create a dynamic title + subtitle using ggplot2

I am using the following code to create a ggplot graph with title and substitle:

This is the code for generating the dataframe

t <- c(1.4,2.1,3.4)
time <- c(10,11,12)
df_match <- data.frame(t, time)


And this is the code for generating the plot.

g <- ggplot(df_match, aes(time, t)) + geom_point()
g + theme(axis.text.x = element_text(angle = 90)) + ggtitle(expression(atop("Head", atop(italic("Location"), ""))))


This works fine. However, when I want to create a dynamic chart and I do:

title <- "Dynamic"


And this:

g <- ggplot(df_match, aes(time, t)) + geom_point()
g + theme(axis.text.x = element_text(angle = 90)) + ggtitle(expression(atop(title, atop(italic("Location"), ""))))


I get "title" as title in stead of "Dynamic". Any thoughts on what goes wrong here?

Answer

Use bquote to evaluate the bits you need evaluated. Put the objects you want evaluated in .()

g + ggtitle(bquote(atop(.(title), atop(italic("Location"), ""))))

Comments