C Tips for using ggtree with ggimage

ggtree supports annotating tree with silhouette images via the ggimage package. ggimage provides grammar of graphic syntax to work with image files. It allows processing images on the fly via the image_fun parameter, which accepts a function to process magick-image object. The magick package provides several functions and these functions can be combined to perform a particular task.

C.1 Example 1: Remove background of images

set.seed(1982)
x <- rtree(5)
p <- ggtree(x) + theme_grey()
p1 <- p + geom_nodelab(image="img/frogs/frog.jpg", geom="image", size=.12) + 
          ggtitle("original image")
p2 <- p + geom_nodelab(image="img/frogs/frog.jpg", geom="image", size=.12,
            image_fun= function(.) magick::image_transparent(., "white")) + 
            ggtitle("image with background removed")
plot_grid(p1, p2, ncol=2)
Remove image background. Plotting silhouette images on phylogenetic tree without (A) and with (B) background remove.

Figure C.1: Remove image background. Plotting silhouette images on phylogenetic tree without (A) and with (B) background remove.

C.2 Example 2: Plot tree on a background image

The geom_bgimage add a layer of the image and put the layer to the bottom of the layer stack. It is a normal layer and doesn’t change the structure of the output ggtree object. Users can add annotation layers as without the background image layer.

ggtree(rtree(20), size=1.5, color="white") + 
  geom_bgimage('img/blackboard.jpg') + 
  geom_tiplab(color="white", size=5, family='xkcd')
Use image file as tree background.

Figure C.2: Use image file as tree background.