I am trying to write a little utility function that will annotate my plots Reuben Fischer-Baum style with a nice little logo and url at the bottom - eg:
I've figured out how to get a postscript file loaded into R; it's justifying the image on the bottom of the plot that's driving me crazy. I can't get the pictureGrob
to left justify; at best I can get it to center on the left hand side of my plot, but half of my image gets cut off, like this reproducible example below:
Tinkering with the width
setting can sort of approximate what I'm trying to accomplish by limiting the buffer around the pictureGrob
, but what I really want, I think, is to left justify the picture itself inside of its viewport OR make the viewport completely snug to the picture. [Paul Murrell does something similar on p. 162 of the grid book, but that seems to depend on a stringWidth
utility function that has no partner for pictures(?)]
I've asked a similar question about gridextra tables, but as baptiste comments there, 'Justification is always rather awkward to handle in grid'.
Any help is appreciated; a pointer to any conceptual discussion of what is happening with justification in grid would be spectacular.
Reproducible code (note that grImport
requires a ghostscript install):
require(grImport)
require(ggplot2)
require(gridExtra)
#nb: you also need ghostscript installed on your machine.
#I had a hell of a time getting ghostscript to work properly.
#From the bowels of a R mailing list, I found this helpful tip
#from Paul Murrell himself:
#https://www.mail-archive.com/[email protected]/msg203180.html
#YMMV, THIS WORKED ON MY MACHINE:
#gswin <- shortPathName("C:/Program Files/gs/gs9.15/bin/gswin64c.exe")
#Sys.setenv(R_GSCMD = gswin)
#get a fun little moon
PostScriptTrace(
file=file.path(system.file(package = "RGraphics"), "extra", "comic_moon.ps"),
outfilename="comic_moon.xml")
moon <- readPicture("comic_moon.xml")
annotate_me <- function(
plot_to_annotate,
some_picture,
bg_color="gray30"
) {
#make a gTree
foo <- gTree(
children=gList(
rectGrob(gp=gpar(fill=bg_color)),
pictureGrob(
picture=some_picture,
x=0, y=0.5,
#width=?
)
)
)
final <- arrangeGrob(
plot_to_annotate, foo,
nrow=2, heights=c(19,1)
)
return(final)
}
annotate_me(
plot_to_annotate=qplot(mpg, data=mtcars),
some_picture=moon
)