Add a logo to your plot

Put a bird on it - Portlandia.

magick
data visualization
ggplot2
Author

Thomas Mock

Published

January 9, 2019

via GIPHY

If you missed out on Portlandia, you should take some time to watch this clip of the “Put a bird on it” episode.

Just like Bryce and Lisa - we can put birds on anything with the magick package from ROpenSci!

So let’s get started putting birds on things!

Magic with magick!

The magick package is an R interface to the ImageMagick STL, one of the most comprehensive open source image processing libraries. It gives a lot of power to R users, and we’ll briefly cover the workflow before getting into our real example.

If you want a deeper dive on all the features of magick, check out their awesome vignette!

# Load the library
library(magick)
Linking to ImageMagick 6.9.12.3
Enabled features: cairo, fontconfig, freetype, heic, lcms, pango, raw, rsvg, webp
Disabled features: fftw, ghostscript, x11
# "read" in an image
dog <- image_read("https://images.pexels.com/photos/1564506/pexels-photo-1564506.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940")

image_info(dog)
  format width height colorspace matte filesize density
1   JPEG  1880   1208       sRGB FALSE    87884   72x72

We can see a few things about the r_logo object, it is a .png, it’s height and width, filesize, and DPI/density.

We can also view the image in line.

print(dog)
  format width height colorspace matte filesize density
1   JPEG  1880   1208       sRGB FALSE    87884   72x72

We also have image manipulation options like image_rotate, image_resize, all of which are pipeable with the %>%.

dog %>% 
  image_rotate(30) %>% # rotate 30 degrees
  image_resize("400x400") %>%  # change size to 400 x 400 pixels
  image_flop() # flip the image horizontally

Most importantly we can put a bird on it!

bird <- image_read("https://user-images.githubusercontent.com/29187501/38769895-edae85d0-3fcf-11e8-95f9-bbd530b32771.png") %>% 
  image_resize("150x150")

image_composite(dog, bird)

Now please note where the bird showed up, in the top left corner. We can control the placement of composite images by specifying the offset.

dog %>% 
  image_composite(bird, offset = "+500+1000")

Notice that offset reads as x-axis pixels, y-axis pixels, so "+500+1000 indicates from the top left corner place the image 500 pixels to the right and 1000 pixels down.

Now that we’ve been oriented to how the magick package works, and had some fun by putting a bird on our lovely Boston Terrier model, let’s dive into the real purpose of this post - adding a logo to your ggplot!