Frits Verstraten
Frits Verstraten

Reputation: 2179

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?

Upvotes: 0

Views: 4320

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269674

Using g and title from the question, try substitute:

g + theme(axis.text.x = element_text(angle = 90)) + 
    ggtitle(substitute(atop(title, atop(italic("Location"), "")), list(title = title)))

giving:

enter image description here

Upvotes: 1

timcdlucas
timcdlucas

Reputation: 1364

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

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

Upvotes: 3

Related Questions