I'm hoping I can combine the spiffy importing and drawing powers of grImport
with the awesome graphing power of ggplot2
, but I simply don't understand the grid
system well enough to find an elegant way of achieving what I want. What I want is to replace the x-axis tick labels in a ggplot2
graph with images imported using grImport
.
Since both packages use grid
functions, I'm hoping there is a way to use grid.symbols()
either within the ggplot2
framework, which would be ideal, or at least on an existing plot in a device. Does anyone with more knowledge of such things know of a robust way to do this? Or, can anyone point me to more information to help me learn about grobs, viewports, etc.? I have read through the free Chapter of Paul Murrel's R graphics book on the Grid graphics model, but I'm not familiar enough with the inner workings of ggplot2 to make the link.
My question is very similar to an existing question about using an image as a plot point, although I'm more interested in the axis labels rather than the plot points. However, I would be curious as to how similar the two tasks are, and if that solution can be adapted for this purpose. I wasn't able to figure it out on my own.
This is my first post, so I'm not allowed to post an image, but this code achieves something close to what I want. Note: this approach uses an ugly, ugly hack that is not portable, and unsatifactory. The final plot I want to produce will have facets (facet_grid
), and the x-axis is for a factor with different pictures at each axis tick, not a continuous variable, which is why I'm looking for a more general / robust solution that doesn't require a lot of trial & error.
library(ggplot2)
## library(grImport) # not needed for this example, but would be for grid.symbols()
p <- ggplot(mtcars, aes(cyl, mpg)) + stat_summary(fun.data = "mean_cl_boot")
print(p)
## Replace (in this case, overlay) x-axis tick labels with a graphic / grob
iconSize <- 0.05
iconHt <- 0.2
padding <- 0.09 # horizontal padding around axis: I found this by trial & error
tickSp <- (1-padding)/(4*2)
downViewport("axis_h-5-3")
## I would use grid.symbols() with an imported Picture in place of grid.circle(),
## but the idea is the same: draw a shape at the ticks along the axis.
for (i in 0:(max(mtcars$cyl) - min(mtcars$cyl)) )
{
grid.circle(x = (padding/2 + tickSp*(i*2)), y = iconHt,
r = iconSize*(min(mtcars$cyl)+i), gp = gpar(fill="black"))
}
upViewport()