Search code examples
rggplot2r-grid

Add sub text to viewport


I would like to add sub text (a textGrob) to a grid Viewport -- is this possible?

I have figured out how to add sub text to a single chart:

require(ggplot2) 
require(gridExtra)

# make the data
timeSeries <- data.frame(date = seq(as.Date("2001-01-01"), as.Date("2012-01-01"), by = "mon"), 
                     value = 1:133 + rnorm(133, 0, 10)
                     )


# make the ggplots
gpLine <- ggplot(timeSeries, aes(x = date, y = value)) +
                geom_line()

gpBar <- ggplot(timeSeries, aes(x = date, y = value)) +
                geom_bar(stat = 'identity')

# ggplot + subtext
grid.arrange(gpBar, sub = textGrob("why is this at the bottom?"))

... And i can stick the two charts together using a grid Viewport

# two plots, one view
vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y)

pushViewport(viewport(layout = grid.layout(3,1)))
print(gpLine, vp = vplayout(1:2, 1))
print(gpBar, vp = vplayout(3, 1))

... but i cannot figure out how to add text to the bottom of the resulting viewport.

Grid is so complete, i'm sure there must be a way, but it's hidden to me.


Solution

  • You are very close:

    popViewport() # brings you to the top viewport for the whole plotting area
    grid.text("Hello Vicar", x = unit(0.5, "npc"), y = unit(0.25, "npc"))
    

    After all your commands above.