How to make xkcd-style plots in R

The webcomic xkcd hits a lot of sweet notes for me, from comedic science communication with Up Goer Five to the importance of labeling your axes.  Fortunately, we live in an age where it is now possible to make xkcd-style plots in R:

fuelefficiencyxkcdWith help from andrew and fibosworld’s posts on R-bloggers, here’s how I did it in Windows:

First, I installed the xkcd font from this site.

Second, in R, I installed and loaded the packages ggplot2 and xkcd.

# Ensuring packages ggplot2 and xkcd installed and loaded
require("ggplot2")
require("xkcd")

Third, I checked that the xkcd font was indeed listed in my system fonts, and imported it into R.  Because I’m using Windows, I also had to load my fonts to the Windows device, so that I could display it graphically.

# Checking xkcd.tff listed among system fonts
font.files()


# Importing the xkcd font into R and confirming it should be imported
font_import(pattern = "[X/x]kcd")
y

# Loading fonts to the Windows device to display graphs on-screen
loadfonts(device = "win")

Finally, I was able to use xkcd-style font and axes to make the plot above!

# Using R's built-in dataset, mtcars, to plot car weight vs. mpg
carPlot geom_point() +
ggtitle("Fuel Efficiency of Cars") +
xlab("Car Weight in Thousands of Pounds") +
ylab("Miles per Gallon") +
xkcdaxis(xrange = range(mtcars$wt), yrange = range(mtcars$mpg)) +
theme(text = element_text(size = 20, family = "xkcd"))


# Plotting, xkcd-style!
carPlot

Advertisements