Skip to Content

Customize Contour Labels in ggplot2

I'm relatively new to ggplot2, and I'm having trouble adding appropriate labels to my contours. I would love to be able to add the labels without the directlabels package, but I haven't found a way to, so if you know of a way to customize labels without directlabels, I would love to here it.

Using the classic volcano example, I can add labels to the default contour plot using the directlabels packet in the following way:

library(plyr)
library(ggplot2)
library(directlabels)
library(reshape)
volcano<-melt(volcano)
v<-ggplot(volcano, aes(x,y,z=z))
e<-v + stat_contour(aes(colour=..level..))
direct.label(e)

In the above example, the labels are added appropriately, but things become more complicated if I try to specify my own break points for the contours:

e<-v + stat_contour(aes(breaks=c(160, 170, 180), colour=..level..))
direct.label(e)

Now, the contours are specified by the breaks I have provided, but labels still appear for all of the default contours. How do I only plot only labels for the graphed contours?

A related issue, how would I plot labels for contour levels not included in the default? Say a break of 165:

e<-v + stat_contour(aes(breaks=c(165), colour=..level..))
direct.label(e)

Thanks for any help!