Using directlabels with ggplot2 to label a second layer with data different from the primary layer

StackOverflow https://stackoverflow.com/questions/20133192

  •  03-08-2022
  •  | 
  •  

Question

I'm using ggplot2 to make contour plots. I'm trying to make a contour plot with split data because I have data from different time periods for different regions of the plot. I'd like to show them on the same plot, but not have the contours line up.

I can produce the contours I want simply enough; here's a similar example:

library(ggplot2)
library(directlabels)
data(volcano)

volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")

#Splitting the data into 2 halves
volcano3d_1<-volcano3d[volcano3d$x<50,]
volcano3d_2<-volcano3d[volcano3d$x>=50,]

#Changing the z values of the 2nd half
volcano3d_2$z<-volcano3d_2$z+30

#Plotting
v <- ggplot(volcano3d_1,aes(x, y, z = z))+
stat_contour(aes(colour = ..level..))+
stat_contour(data=volcano3d_2,aes(x,y,z=z,colour=..level..))
direct.label(v)

However, I can't get direct.label to add labels to the second part of the map. It seems like the difficulty is with getting it to label a layer that has data different from the primary ggplot layer. Does anyone know of a way I can make it label both layers?

Was it helpful?

Solution

Use geom_dl to label additional layers:

WithLegend <- ggplot(volcano3d_1,aes(x, y, z=z, colour=..level..))+
  stat_contour()+
  stat_contour(data=volcano3d_2)
## direct.label labels the first colored layer.
SomeLabels <- direct.label(v)
## Additional labels can be added using geom_dl layers.
MoreLabels <- SomeLabels+
  geom_dl(aes(label=..level.., colour=..level..),
          data=volcano3d_2, method="top.pieces", stat="contour")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top