Andy Clifton
Andy Clifton

Reputation: 5066

Add filename or other annotation to ggplot figures

I use ggplot to make most of my graphics. These can be single panels, or faceted. To make it easier to track revisions, I would like to generate a small label in the corner of the plot that includes some text.

In pseudo code, I am looking for something like this:

# generate the initial plot
p <- ggplot()
# add the label
p + someAnnotationFunction(label = "Version 1.0", x = 1, y = 0, 
                           hjust = "right", vjust = "bottom" )
# print
print(p) 

Or: plot my label nestled in the lower right corner of my figure without messing up the existing ggplot graphics.

So far I'm not having any luck finding a solution. This (very interesting) method doesn't work if you have a full m x n table of facets. Methods using gridExtra tend to mess with the plots too much. So, does anyone have a way to add arbitrary text anywhere on a plot that was generated using ggplot?

Upvotes: 3

Views: 1697

Answers (2)

A Toll
A Toll

Reputation: 807

By making a data frame of your annotations, you can add them on top of your plot using geom_text.

note <- data.frame(xVarName = c(1, 5), yVarName = c(1, 10), 
    text = c("Version 1.0", "April 26, 2014")

 p + geom_text(data = anno, aes(label = text))

"Version 1.0" will show up in the bottom left and "April 26, 2014" will show up in the top right.

By making your notes in a separate dataframe, you can add multiple notes to one graph if desired.

Upvotes: 1

Andy Clifton
Andy Clifton

Reputation: 5066

Here's a worked solution using gridExtra(), based on Baptiste's comment:

require("ggplot2")
require("gridExtra")

# set our working directory 
working.dir <- '/Users/aclifton/Documents/projects/Rcode' 
setwd(working.dir)

# create a data frame
df <- data.frame(x =runif(100, 1, 10),
                 y = runif(100, 1, 10))
#create a plot
p <- ggplot(data = df,
            aes(x = x,
                y = y)) +
  geom_point()

print(p)        

We now have our plot, and the trick is adding that label and saving the overall plot using ggsave():

# label to show
sub.label = textGrob("Some kind of label", 
               gp=gpar(fontsize=6),
               x = unit(1, "npc"),
               hjust = 1,
               vjust = 0)

ggsave(filename=file.path(working.dir,'DemoPlot.png'),
       plot = arrangeGrob(p,
                          sub = sub.label,
                          clip = FALSE),
       scale = 1,
       width = 6.5,
       height = 3.5, 
       units = c("in"),
       dpi = 300)

Which gives you this: enter image description here

Upvotes: 2

Related Questions