Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to Label Specific Contours using direct.label

Tags:

r

ggplot2

contour

I'm relatively new to ggplot2, and I'm having trouble adding appropriate labels to my contours.

Using the classic volcano example, I can add labels to the default contour plot:

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!

like image 638
Burton Guster Avatar asked May 20 '12 17:05

Burton Guster


2 Answers

I couldn't stand to see an old question unanswered with such an easy fix.

The simple problem was the mapping inside stat_contour(). Your call should be:

v<-ggplot(volcano, aes(x=X1,y=X2,z=value))  # specify the mapping properly
e<-v + stat_contour(aes(colour=..level..), breaks=c(160, 170, 180))
direct.label(e)

With the breaks not included in the aes mapping, and the colour=..level.. included.

enter image description here

like image 110
a different ben Avatar answered Oct 12 '22 10:10

a different ben


with ggplot > 2.0.0 you'll need to add method="bottom.pieces" (or top.pieces) to the direct.label call

library(directlabels)
direct.label(e, method="bottom.pieces")
like image 23
LiveLongandProsper Avatar answered Oct 12 '22 09:10

LiveLongandProsper