Skip to content

Instantly share code, notes, and snippets.

@luisDVA
Last active April 17, 2017 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luisDVA/101374d9d6b569d887a1a2c7654cd3a4 to your computer and use it in GitHub Desktop.
Save luisDVA/101374d9d6b569d887a1a2c7654cd3a4 to your computer and use it in GitHub Desktop.
place two random dog images next to a ggplot object
# define function
# this code is just for fun and I do not have rights to the images on dogtime.com I just like dogs
ggpup <- function(ggplotObject){
# required packages
require(dplyr)
require(jpeg)
require(grid)
require(gridExtra)
require(RCurl)
require(rvest)
require(stringi)
require(extrafont)
# scrape a list of image URLS from the dogtime breed profiles homepage
if (!exists("imgurls")){
# read page source
dogIndex <- read_html("http://dogtime.com/dog-breeds/profiles")
# keep node of interest (identified using Selectorgadget)
scrapedHtml <- dogIndex %>% html_nodes(".horizontal-group-listing") %>% toString()
# match image urls
## Find everything that starts with "http"
### No white spaces allowed
### Ends with jpg
#### Note: this regex is for PC
imgurlslist <- stri_match_all_regex(scrapedHtml,"(http[^\\s]+(jpg)\\b)")
# subset into character vector
imgurls <- imgurlslist[[1]][,1]
}
# scrape two dog breed photos (randomized)
urlInd <- sample(length(imgurls),2,rep=F)
# for upper right corner
dogImg.URLU <- imgurls[urlInd[1]]
# save as a raster object
dogImgU <- rasterGrob(readJPEG(getURLContent(dogImg.URLU)))
# for lower right corner
dogImg.URLL <- imgurls[urlInd[2]]
# save as a raster object
dogImgL <- rasterGrob(readJPEG(getURLContent(dogImg.URLL)))
# graphical parameters
# define plot layout
lay <- rbind(c(1,1,2),
c(1,1,3))
# set up some attribution text
# the fontfamily parameter is optional, erase or change to something else to match the fonts available for your system
rightText=textGrob("images from www.dogtime.com", rot=90, gp=gpar(fontfamily = "Roboto Condensed Light"))
# arrange the plot and the image side by side
grid.arrange(ggplotObject, dogImgU, dogImgL, layout_matrix=lay,widths=c(2,1,1),right=rightText)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment