Skip to content

Instantly share code, notes, and snippets.

@bergeycm
Created August 29, 2014 17:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bergeycm/4782dbd49b39efd3c729 to your computer and use it in GitHub Desktop.
Save bergeycm/4782dbd49b39efd3c729 to your computer and use it in GitHub Desktop.
R function to grab a random picture of a cat and a random quote from Dune and plot them together.
plot.kitty = function () {
library(jpeg)
temp.cat = tempfile()
download.file("http://thecatapi.com/api/images/get?format=src&type=jpg",
destfile=temp.cat)
kitty = readJPEG(temp.cat)
# Get dimensions
kitty.h = dim(kitty)[1]
kitty.w = dim(kitty)[2]
kitty.ratio = kitty.h / kitty.w
par(mar=rep(1, 4))
# Only plot if version of R supports it
if (exists("rasterImage")) {
plot(0:1, 0:1, type='n', xaxt='n', yaxt='n')
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = "black")
# If image is lanscape, set width to be 0.6 and compute height
if (kitty.w > kitty.h) {
center.x = 0.5
x.limits = c(center.x - 0.3, center.x + 0.3)
width = x.limits[2] - x.limits[1]
height = width * kitty.ratio
center.y = 1 - (1.5 * height / 2)
y.limits = c(center.y - (height / 2), center.y + (height / 2))
} else {
# Otherwise, set height to be 0.6 and compute width
center.y = 1 - (0.6 / 2)
y.limits = c(center.y - 0.3, center.y + 0.3)
height = y.limits[2] - y.limits[1]
center.x = 0.5
width = height / kitty.ratio
x.limits = c(center.x - (width / 2), center.x + (width / 2))
}
rasterImage(kitty, x.limits[1], y.limits[1], x.limits[2], y.limits[2])
add.quote()
}
}
add.quote = function () {
library(rjson)
json.url = "http://iheartquotes.com/api/v1/random?format=json&max_lines=5&max_characters=100000&source=dune"
json.data = fromJSON(paste(readLines(json.url), collapse=""))
quote = json.data$quote
# Get rid of newlines
quote = gsub("\\n", "", quote)
# And escaped quotes
quote = gsub('\\"', "", quote)
# And the source info
quote = gsub("-from.*", "", quote)
json.wrap = paste(strwrap(quote, width=10 * dev.size("in")[1]), collapse="\n")
text(0.501, 0.201, bquote(.(json.wrap)), col="grey")
text(0.5, 0.2, bquote(.(json.wrap)), col="white")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment