Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding custom labels to ggplot geom_contour

Tags:

r

ggplot2

I'm trying to make a contour plot with specified breaks and labels at those breaks. I tried to add labels at the breaks using either direct.label or geom_dl, but failed.

dat <- melt(volcano)
brks <- c(100, 120, 140, 160)
g <- ggplot(dat, aes(x = Var1, y = Var2, z = value)) +
  geom_contour(colour = 'black', breaks = brks)
g

That part works fine, but when I try to add the labels:

direct.label(g, list("bottom.pieces", colour='black'))

I receive the error: Need colour or fill aesthetic to infer default direct labels.

And, when I try:

g + geom_dl(aes(label = brks),  method = 'bottom.pieces')

I get: Error: Aesthetics must be either length 1 or the same as the data (5307): label, x, y, z

Any suggestions?

like image 701
Lukas Avatar asked May 16 '26 17:05

Lukas


1 Answers

I think that I have come to a workaround to show the labels using geom_dl:

library(lattice)
library(directlabels)
dat <- melt(volcano)
brks <- c(100, 120, 140, 160)
g <- ggplot(dat, aes(x = Var1, y = Var2, z = value)) +
     geom_contour(colour='black', breaks = brks)+
     geom_dl(aes(label=..level..), method="bottom.pieces", 
             stat="contour",breaks = brks)
g

Just indicate in geom_dl that you want to label the levels (aes(label=..levels..)) contained in the breaks (breaks=brks), so it knows the labels to be shown.

like image 140
Mabel Villalba Avatar answered May 18 '26 11:05

Mabel Villalba