ggplot2 cheatsheet

These are some of the most common things I want to do with ggplot2, but always forget the syntax (not helped when things are still evolving with each release!)

Titles, axis labels

  • main title
+ ggtitle("...")
  • set axis title (but see scale_x_continuous below)
+ xlab("...")
  • remove axis title, labels and tick marks (respectively)
+ theme(axis.title.x=element_blank(), 
  • make axis labels at a 45 degree angle
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
  • customize axis breaks and labels. title is optional, labels are optional and default to as.character(breaks)
scale_x_continuous("x axis title (optional)",
  • stretch axis to full width/length of plot


  • no legend
+ theme(legend.position="none")

ggheatmap, version 2

It looks like my ggplot2 heatmap function gets most traffic on this blog. That’s a bit unfortunate, because it’s the first function I wrote in earnest using ggplot2 and ggplot2 itself has undergone some updates since then, meaning my code is clunky, outdated and, er, broken.

So, with a bit more knowledge of ggplot2 and grid gained over the last few months, I have updated it today, and it is working. I hope it’s useful!

Get the code from github, and run it with

## simulate data
sigma[1:4,1:4] <- 0.6
sigma[6:10,6:10] <- 0.8
diag(sigma) <- 1
X <- rmvnorm(n=100,mean=rep(0,10),sigma=sigma)

## make plot
p <- ggheatmap(X)

## display plot

The result should look something like

Using ggplot2 in a package

Due to my recent conversion to ggplot2, I am starting to use ggplot() in packages. Running R CMD check on this function


I got the note

* checking R code for possible problems ... NOTE
colocpc.plot: no visible binding for global variable ‘v’

It turns out this is a known feature of the R checking code. v is indeed undefined. I like a clean run of R CMD check --as-cran for all packages. The link gives a discussion of alternative work-arounds:

Continue reading

pch symbols

I often have used simple code like this to remind myself which number corresponds to which pch character:

plot(x, y, type="n", ylab="", xlab="pch", axes=FALSE)


I wondered what it would take to do the same in ggplot2. The amount of typing required to remove (most of) the y axis kinda annoys me, but otherwise, it’s quite nice:

ggplot(data.frame(x=x,y=y), aes(x=x,y=y,pch=as.factor(x))) +
  geom_point() +
  xlab("pch") + ylab("") +
  scale_shape_manual(values=1:25) +
       axis.title.y = theme_blank(),
       axis.text.y =  theme_blank() )